[Python-Dev] Unbound locals in class scopes

Ron Adam ron3200 at gmail.com
Sat Jun 20 18:12:57 CEST 2015



On 06/20/2015 02:51 AM, Ivan Levkivskyi wrote:
> Hello,
>
> There appeared a question in the discussion on
> http://bugs.python.org/issue24129 about documenting the behavior that
> unbound local variables in a class definition do not follow the normal rules.
>
> Guido said 13 years ago that this behavior should not be changed:
> https://mail.python.org/pipermail/python-dev/2002-April/023428.html,
> however, things changed a bit in Python 3.4 with the introduction of the
> LOAD_CLASSDEREF opcode. I just wanted to double-check whether it is still a
> desired/expected behavior.


Guido's comment still stands as far as references inside methods work in 
regards to the class body. (they must use a self name to access the class 
name space.) But the execution of the class body does use lexical scope, 
otherwise it would print xtop instead of xlocal here.

x = "xtop"
y = "ytop"
def func():
     x = "xlocal"
     y = "ylocal"
     class C:
         print(x)
         print(y)
         y = 1
func()

prints

xlocal
ytop


Maybe a better way to put this is, should the above be the same as this?

 >>> x = "xtop"
 >>> y = "ytop"
 >>> def func():
...     x = "xlocal"
...     y = "ylocal"
...     def _C():
...         print(x)
...         print(y)
...         y = 1
...         return locals()
...     C = type("C", (), _C())
...
 >>> func()
xlocal
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 9, in func
   File "<stdin>", line 6, in _C
UnboundLocalError: local variable 'y' referenced before assignment

I think yes, but I'm not sure how it may be different in other ways.


Cheers,
    Ron




More information about the Python-Dev mailing list