2
$\begingroup$

Apologies for the long question title, but I couldn't come up with something shorter to describe the following. Starting with a clean session, there are no symbols in, let's say, myContext:

Names["myContext`*"]
(* {} *)

But if I now evaluated this If statement,

If[False, myContext`mySymbol = "value"]

all of the sudden mySymbol has been created in myContext:

Names["myContext`*"]
(* {"myContext`mySymbol"} *)

but, as expected, mySymbol doesn't have a value:

myContext`mySymbol
(* myContext`mySymbol *)

My question is twofold: why has mySymbol been created, and how can I prevent this from happening?

$\endgroup$
5
  • $\begingroup$ this is probably related to how just mentioning a symbol appears to add it to the symbol list. If you run a line with just blah, blah is added as a symbol. i don't know what the purpose of that is. maybe it's to make Options symbols (such as Automatic) show up in black instead of blue $\endgroup$
    – amr
    Jul 26 '13 at 19:53
  • 2
    $\begingroup$ Symbols are added to the context at parsing stage, not evaluation. So just reading that line is sufficient to create it. This is why when you use functions from a package that is loaded inside a function or using initializations, you should use the full context name of the function so that the parsing stage creates it in the appropriate context. Otherwise, it leads to shadowing. $\endgroup$
    – rm -rf
    Jul 26 '13 at 20:07
  • $\begingroup$ Teake, I've marked this question "already has an answer here." Please take a look at that Q&A and let me know if anything remains unanswered. $\endgroup$
    – Mr.Wizard
    Jul 26 '13 at 20:10
  • $\begingroup$ Also see this question and its answers $\endgroup$
    – rm -rf
    Jul 26 '13 at 20:18
  • $\begingroup$ @Mr.Wizard Thanks, that Q&A and the above comments clarify everything. $\endgroup$ Jul 26 '13 at 21:00

Browse other questions tagged or ask your own question.