There are two things that influence symbol lookup: $ContextPath
and $Context
. This is described in:
In short: $ContextPath
controls where the system looks for existing symbols. This search is done first. $Context
controls where new symbols are created if a name was not found in $ContextPath
any contexts.
Begin
changes only $Context
. BeginPackage
changes both $ContextPath
and $Context
.
You are only using Begin
, but not BeginPackage
. This means that $Context
will be set to "Test`"
but $ContextPath
will stay what it was before.
When you mention a symbol name such as f
, the first thing Mathematica does is that it looks for it in the contexts contained in $ContextPath
. If it is found there, it uses that instance. This is what happens during the second evaluation: f
is found in Global`
, so f
now refers to Global`f
, not Test`f
.
Why does f
exist in Global`
? Because you mentioned it when evaluating f[2]
. Note the distinction between the fact that a symbol exists and that a symbol has associated definitions. Just evaluating sym
alone will create that symbol.
f[2]
that is followed by the comment returns unevaluated, as it should. Then,Test f[2]
returns evaluated, as it should. What is the issue? $\endgroup$Global`f
is already created, so you are assigning to it, instead ofTest`f
. $\endgroup$