6
$\begingroup$

In the following the full context form of Test is not required as "Aaa`" is added to $ContextPath

Aaa`Test[x_] := x + 1;
context = "Aaa`";
PrependTo[$ContextPath, context];
Context@Test

(* "Aaa`" *)

The same however, doesn't seem to apply within scoping constructs.

Quit
Aaa`Test[x_] := x + 1;
With[{context = "Aaa`"},
 PrependTo[$ContextPath, context];
 Context@Test
 ]

(* "Global`" *)

Note that Quit is needed as the expected behaviour happens if evaluated twice. I find this surprising as it indicates an a priori parsing of the body within scoping constructs (the same applies if With is replaced by Block or Module) whereas I would have anticipated that this would be changeable along with normal control-flow expectations. Is this a bug or a feature?

$\endgroup$
2
  • $\begingroup$ Related: Context of localized (dynamic) symbols, Local variables in Module leak into Global context. Although those questions focus on Module, With is also a scoping construct. $\endgroup$
    – MarcoB
    Commented Jan 17, 2021 at 5:27
  • $\begingroup$ @MarcoB Those links describe a slightly different situation describing conflicting local/global variables. They did however, contain a couple of relevant answers (now linked in the self-answer) that led to correcting clearly a long-held misunderstanding of WL's evaluation sequence. Thanks! $\endgroup$ Commented Jan 17, 2021 at 8:45

1 Answer 1

2
$\begingroup$

The scoping construct is only relevant in so far as it groups the code into a singly parsed block. Hence, the same "unexpected" behaviour results from any type of grouping

(Aaa`Test[x_] := x + 1;
 context = "Aaa`";
 PrependTo[$ContextPath, context];
 Context@Test
 )

(* "Global`" *)

Hence, the WL possesses a parsing/evaluation sequence from input to input (line to line) giving a hybrid parsing/run-time evaluation sequence (n.b. loading the first snippet in a .m/.wl file produces identical output). If all needs to be contained in a given scope one workaround as per this answer is to delay the parsing with strings/boxes although probably easier is just to set up desired contexts in a previous input.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.