baffled classes within a function namespace. Evaluation order.

Peter Otten __peter__ at web.de
Fri Apr 26 03:15:51 EDT 2013


Steven D'Aprano wrote:

> On Fri, 26 Apr 2013 07:39:32 +0200, Peter Otten wrote:
> 
>> A class body is basically a function body that is executed once. To
>> allow an assignment
>> 
>>>>> x = 42
>>>>> class A:
>> ...     x = x
>> ...
>> 
>> which is not possible inside a function
> 
> 
> As far as I can tell, the documentation says that this assignment should
> also be impossible inside a class. Unless I'm missing something, I think
> this is a bug.
> 
> http://docs.python.org/3/reference/executionmodel.html
 
Will have a look.
 
> [...]
>> However, while the above gives some technical background it doesn't
>> explain why this scheme was chosen. My guess is that when Python got
>> closures nobody was willing to do the extra work to make class bodies
>> namespace-aware. The alternative, disallowing x = x in classes, would
>> have seriously broken backwards-compatibility.
> 
> Not so. x = x was not allowed in classes before there were closures:
> 
> 
> [steve at ando ~]$ python1.5
> Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat
> 4.1.2-52)] on linux2
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>>
>>>>
>>>> def f():
> ...     x = 1
> ...     class Test:
> ...             x = x
> ...     return Test
> ...
>>>> T = f()
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 3, in f
>   File "<stdin>", line 4, in Test
> NameError: x

Define a global variable x and run it again. I don't have an ancient Python 
lying around but my "prediction" is

>>> x = 42
>>> f().x
42

which would be the same behaviour as that of Python 3.3.





More information about the Python-list mailing list