[Cython] Class scope lookup order

Stefan Behnel stefan_ml at behnel.de
Mon Aug 15 11:34:25 CEST 2011


Vitja Makarov, 15.08.2011 07:49:
> 2011/8/15 Vitja Makarov:
>> When creating python-class dict it seems that CPython first looks at
>> dict then at globals:
>>
>> A = 1
>> class X:
>>     A = A
>>
>> def y():
>>     A = 3
>>     class Y:
>>         A = A
>>     return Y
>> Y = y()
>>
>> print(X.A, Y.A)
>>
>> Will print: 1, 1
>> And not: 1, 3
>>
>> I didn't find documentation for this but if I'm correct that should be
>> easy to fix issue in Cython.
>>
>> Now for this code cython reports compile-time error: local variable
>> referenced before assignment
>
> One more interesting example:
>
> A = 1
> def foo(a):
>      A = a
>      class X:
>          a = A
>          A = A
>      class Y:
>          a = A
>      return X, Y
> X, Y = foo(666)
> print X.a, X.A, Y.a

This prints "1 1 666". However, at least to me, the most surprising thing 
is this:

   >>> A = 1
   >>> def foo(x):
   ...     A = x
   ...     class X:
   ...         a = A
   ...     return X
   ...
   >>> foo(2).a
   2
   >>> def foo(x):
   ...     A = x
   ...     class X:
   ...         A = A
   ...     return X
   ...
   >>> foo(2).A
   1

That looks pretty sick, but I would guess that the 'reasoning' behind this 
is that the second case contains an assignment to A inside of the class 
namespace, and assignments make a variable local to a scope, in this case, 
the function scope. Therefore, the A on the rhs is looked up in that scope 
as well. However, this is just a hand waving guess. I just asked on c.l.py, 
we may get a pointer to relevant documentation that way.

Also see this bug:

http://trac.cython.org/cython_trac/ticket/671

Stefan


More information about the cython-devel mailing list