如果我们逐一评估这些行,将在上下文 cc
中创建 x
。
Begin["cc`"];
x = 1;
End[]
但是,如果我们一起评估它们,
(Begin["cc`"];
x = 1;
End[])
则将在 Global
中创建 x
。尽管有以下打印cc`
:
(Begin["cc`"];
Print[$Context];
End[])
此行为的原因是什么?我的猜测是上下文仅在解析阶段重要,而不是评估阶段。
用例:我想创建一个调色板 Button
,它将在“私有”上下文中定义一些符号(如果它们尚不存在),以避免与全局冲突。除了将所有定义放入包文件并从调色板加载之外,执行此操作的首选方法是什么? (我想保持调色板独立。)
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.)
发布评论
评论(3)
符号(及其上下文)是在解析时创建的,而不是在求值时创建的。如果我们使用 $NewSymbol ,我们可以看到效果:
第一个打印:
因为单元格中的每一行都被视为单独的输入。第二个使用括号强制所有三行被视为一个输入并打印
,从中我们可以看到
test2
是在发生任何评估之前在Global`
上下文中创建的。我认为最简单的处理方法是在符号上使用显式上下文:
cc`x = 1
。Symbols (and their contexts) are created when parsing, not evaluation. If we use
$NewSymbol
we can see this in effect:The first one prints:
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
from which we can see that
test2
was created in theGlobal`
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
.对于你的第二个问题,我建议你参考这个答案我的,它可以有效地自动执行您概述的步骤(使用 ParseTimeNameSpaceWrapper 函数)。它可能需要更多的工作来使其更加强大,但这可能是一个起点。我自己有时也用这个东西。
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: