Class-level variables - a scoping issue
ixokai at ixokai.io
Tue Oct 12 00:25:08 CEST 2010
On 10/9/10 10:30 PM, John Nagle wrote:
> Python protects global variables from similar confusion
> by making them read-only when referenced from an inner scope
> without a "global" statement.
No. It doesn't. Assignments simply always apply to local variables,
unless you explicitly indicate otherwise. There is no "protection" going
Its the exact same principle of what's going on with classes/instances;
assignment to an instance always apply to variables local to that
instance-- and not global to the class-- unless you explicitly indicate
There is no protection of the global going on: in all cases, you can
create a new local variable that shadows the global that was previously
The syntax is just different. For regular, free variables, you
"explicitly indicate otherwise" by using the global statement. For
class/instance variables, you "explicitly indicate otherwise" by doing
class.var or self.__class__.var = whatever.
Yes, the behavior of "get" and "set" are distinctly different. "get" in
all cases -- both free variables in functions, and when getting
attributes from your instance -- looks up the tree, starting at your
most local namespace and walking up until it finds what you want. For
free variables, this is a short list: locals(), enclosing nested
function scopes, globals(), builtins.
For attributes, it starts on your instance, then goes to the class, then
up the superclass tree.
The "sets" in all cases don't walk up the tree at all. They only set in
the most local namespace, unless again, you explicitly tell it to do
Sure, this means you can accidentally shadow a global and run into
problems. It also means you can forget that "explicitly tell it" and run
into other problems.
But its still a feature, and basically part of the core, fundamental
object model of Python.
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 487 bytes
Desc: OpenPGP digital signature
More information about the Python-list