Need help with Python scoping rules

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 27 08:25:36 EDT 2009


Jean-Michel Pichavant a écrit :
> kj wrote:
>> I think I understand the answers well enough.  What I *really*
>> don't understand is why this particular "feature" of Python (i.e.
>> that functions defined within a class statement are forbidden from
>> "seeing" other identifiers defined within the class statement) is
>> generally considered to be perfectly OK.  IMO it's a bizarre,
>> inexplicable blindspot (which, among other things, gives rise to
>> a certain worry about what other similar craziness lurks under
>> Python's image of rationality).  I have never seen even a half-hearted
>> justification, from a language design point of view, for why this
>> particular "feature" is worth having.  Maybe some day the BDFL will
>> deign to give one.
>>
>> kynn
>>   
> 
> I think I got your point.
> I guess many people may not be receptive to your question, cause guess 
> what, we're all python fans :o)
> 
> in foo.py:
> 
> a = 5
> b = a # works fine
> 
> class A:
>    c = 5
>    d = c # broken

Err... Did you actually tried this ?


 >>> class A:
...     c = 5
...     d = c
...
 >>> A.c
5
 >>> A.d
5
 >>>


>    d = A.c # broken either

Not "broken" : the class doesn't yet exists, nor is it bound to global 
name 'A'. FWIW, *this* works (for some definitions of 'works') juts fine:

 >>> class Foo(object):
...     c = 42
...
 >>> A = Foo()
 >>> class A(object):
...     d = A.c
...
 >>> A.d
42



> 
> We should all acknowledge that any newcomer to python will not expect 
> such behavior.

Any newcomer to any language should aknowledge that her expectations 
based on previous experience with any other language should be kept 
aside or just plain abandoned, and start by learning the new language.

The only thing one is entitled to expect when learning a new language is 
that the language's implementation follows the language specs.

> There are plenty of good answers to that thread 
> explaining why the fact that classes are not scopes is much better. 
> Still this design fails at one point : insight.

Oh, really ?

> It may be solved by creating the class upon the "class" statement. If 
> the class A object is created, then c is added as a property of that 
> object, there's no problem accession one object property with A.c.

Please, write a pep...



More information about the Python-list mailing list