If we evaluate these lines one-by-one, x
will be created in the context cc
.
Begin["cc`"];
x = 1;
End[]
However, if we evaluate them together,
(Begin["cc`"];
x = 1;
End[])
then x
will be created in Global
. This is despite the following printing cc`
:
(Begin["cc`"];
Print[$Context];
End[])
What is the reason for this behaviour? My guess is that contexts only matter during the parsing phase, not evaluation.
Use case: I wanted to create a palette Button
that will define some symbols if they don't exist yet, in a "private" context to avoid conflict with globals. What is the preferred method to do this, other than putting all the definitions in a package file and loading them from the palette? (I'd like to keep the palette self-contained.)
Although it may sound foreign to the ear, the phrase “whether it be” is grammatically correct. It often describes conditional or imaginary situations, which is why it can be confusing, especially to an English second language speaker. The correct use of the phrase “whether it be” would be in a formal context.
We use whether in indirect yes-no questions and questions with or. We can't leave out whether (or if): They asked me whether (if) I was tired.
Examples. “My mother asked whether or not I had done my homework.” “It was so rainy outside that the weather announcer wondered whether or not fish were swimming across the street.” The second of these examples is a more complex sentence, but in both the pattern holds.
Symbols (and their contexts) are created when parsing, not evaluation. If we use $NewSymbol
we can see this in effect:
$NewSymbol=Print["Name: ",#1," Context: ",#2]&;
Print["first"];
test1;
Print["last"]
(Print["first"];
test2;
Print["last"])
The first one prints:
first
Name: test1 Context: Global`
last
because each line in the cell is treated as a separate input. The second one uses parentheses to force all three lines to be considered one input and prints
Name: test2 Context: Global`
first
last
from which we can see that test2
was created in the Global`
context before any evaluation occurred.
I think the easiest way to work with this is to use an explicit context on your symbol: cc`x = 1
.
For your second question, I refer you to this answer of mine, which effectively automates the steps you outlined (with the ParseTimeNameSpaceWrapper
function). It may need more work to make it more robust, but that could be a starting point. I use this stuff myself on occasion.
Just for reference:
(Begin["cc`"]; Evaluate[Symbol["x"]] = 1; End[])
cc`x
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With