Need help with Python scoping rules

Miles Kaufmann milesck at umich.edu
Thu Aug 27 23:27:23 EDT 2009


On Aug 27, 2009, at 4:49 PM, kj wrote:

> Miles Kaufmann <milesck at umich.edu> writes:
>> Guido's design justifications:
>> http://mail.python.org/pipermail/python-dev/2000-November/010598.html
>
> Ah!  Clarity!  Thanks!  How did you find this?  Did you know of
> this post already?  Or is there some special way to search Guido's
> "design justifications"?

I just checked the python-dev archives around the time that PEP 227  
was written.

>> ...because the suite
>> namespace and the class namespace would get out of sync when  
>> different
>> objects were assigned to the class namespace:
>
>> class C:
>> x = 1
>> def foo(self):
>>     print x
>>     print self.x
>
>>>>> o = C()
>>>>> o.foo()
>> 1
>> 1
>>>>> o.x = 2
>>>>> o.foo()
>> 1
>> 2
>
> But this unfortunate situation is already possible, because one
> can already define
>
> class C:
>  x = 1
>  def foo(self):
>      print C.x
>      print self.x
>
> which would lead to exactly the same thing.

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:

    # In a hypothetical Python with nested class suite scoping:
    class C:
        x = 1
        @classmethod
        def foo(cls):
            print x
            print cls.x

    >>> C.foo()
    1
    1
    >>> C.x = 2
    >>> C.foo()
    1
    2

With your example, the result is at least easily explainable: self.x  
is originally 1 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).  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).

-Miles




More information about the Python-list mailing list