Need help with Python scoping rules

Xavier Ho contact at
Fri Aug 28 05:48:31 CEST 2009

On Fri, Aug 28, 2009 at 1:27 PM, Miles Kaufmann <milesck at> wrote:

> You're right, of course.  If I had been thinking properly, I would have
> posted this:
> ... the suite namespace and the class namespace would get out of sync when
> different objects were assigned to the class namespace:

I'm not an expert on Python, but could you define "out of sync" for me? When
you call the class as a new instance and assign it to a new variable, the
class attributes (self.x) are independent for each instance. The static
variables in the class (x, or C.x in this case) is shared between all
instances of this class.

>   # In a hypothetical Python with nested class suite scoping:

Class already provides some kind of scoping/namespace, that is the locals()
method for the class. What is pypothetical about this, if you could

<snips the code>

With your example, the result is at least easily explainable: self.x is
> originally 1

Incorrect. "self.x" (or cls.x in your sample code) doesn't exist until you
called o.x = 2, which sets "cls.x = 2".

Don't be confused between static variables that are initialised at class
creation, and the class attributes which usually is declared inside the
__init__ method.

> because the object namespace inherits from the class namespace, but running
> 'o.x = 2' rebinds 'x' in the object namespace (without affecting the class
> namespace).

See above comment.

> It's a distinction that sometimes trips up newbies (and me, apparently ;)
> ), but it's straightforward to comprehend once explained.  But the
> distinction between the class suite namespace and the class namespace is far
> more subtle; extending the lifetime of the first so that it still exists
> after the second is created is, IMO, asking for trouble (and trying to unify
> the two double so).

It is. I had trouble getting it also, but once I think of all the variables
outside of the __init__() method as "static", and the ones within as "class
attributes", everything clears out just fine. =]

Any corrections appreciated. I'm merely posting my understanding of Python.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list