Python, Parrot, and Lexical Scopes
I've been trying to make sense of Python's scoping in the context of Parrot. Whereas Dan saw two types of variables, I see three: builtin, module, and lexical. Consider the following scope1.py:
from scope2 import * print f(), foo foo = 1 print f(), foo
and scope2.py:
foo = 2 def f(): return foo
The expected output is:
2 2 2 1
I find in discussions such as these , the hardest part is finding a common vocabulary. So instead of trying to express this in prose, I'll express it in Perl terms:
our $__name__ = "main"; { package scope2; our $__name__ = "scope2"; our $foo = 2; our $f = sub { $foo }; } *foo = \$scope2::foo; *f = \$scope2::f; print &$f(), " $foo\n"; *foo = \1; print &$f(), " $foo\n";
What does this mean?
- Every Python function in a module, and therefore every Python function, is a closure.
- Not shown above, but at depth zero of every scratchpad stack would be all the Python builtins.
- The above Perl is not precisely accurate: scope2 would be created with a newpad(1), copying over the builtins but never attaining visibility to the importer's symbols.
- It is highly desirable that the
foo = 1
andfoo = 2
statements above generate the same Parrot code. - Globals would be a convenient place to keep track of the loaded modules.
- While I see operations for creating and manipulating lexical
stacks, I don't see operations for setting, saving, and restoring
the current context, as the
f
function above would need to do.
I am going to post this to the perl6 internals list for discussion.