Class-level variables - a scoping issue

Ixokai ixokai at ixokai.io
Mon Oct 11 18:25:08 EDT 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
on here.

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
otherwise.

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
there.

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
something else.

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.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20101011/f24af6f7/attachment.sig>


More information about the Python-list mailing list