Python scope is too complicated
jfj at freemail.gr
Sun Mar 20 23:34:23 CET 2005
> Yeah, I know. It's the price we pay for forsaking variable declarations.
> But for java programmers like me, Py's scoping is too complicated.
> Please explain what constitutes a block/namespace, and how to refer to
> variables outside of it.
Some may disagree, but for me the easiest way to understand python's
scopes is this:
"""In Python, there are only two scopes. The global and the local.
The global scope is a dictionary while the local, in the case of a
function is extremely fast. There are no other scopes. There are
no scopes in the nested statements inside code blocks and there are
no class scopes. As a special case, nested function definitions
appear to be something like a nested scope, but in reallity this is
detected at compile-time and a strange feature called 'cell variables'
In order to write to a global variable from a function, we have
which notifies the compiler that assignment to 'var' does not make
a new local variable, but it modifies the global one (OT: wouldn't
"global.var = 3" be nicer?). On the other hand, if we just want to
read a global variable we don't have to say "global var" because
the compiler sees that there is no assignment to 'var' in the function
code and therefore intelligently concludes that it's about a global
Generally, python sees everything as
exec "code" in global_dictionary, local_dictionary
In this case it uses the opcode LOAD_NAME which looks first in locals
and then in globals (and actually, then in __builtins__)
For functions it uses either LOAD_FAST for locals or LOAD_GLOBAL for
More information about the Python-list