NameError assigning to class created in a function
Duncan Booth
duncan at NOSPAMrcp.co.uk
Wed Mar 20 03:58:39 EST 2002
[posted and mailed]
Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote in
news:mailman.1016603731.25922.python-list at python.org:
> So, it seems that you can't assign to a variable in a class if it has the
> same name as the variable you are assigning from. Except that it works
> outside a function:
>
It seems to be a problem with nested scopes. If a variable is assigned to
anywhere in the class statement, then the local value is used after the
assignment, but the global value is used before. If a variable is not
assigned to then the nested scope rules apply.
def f(y):
class Private:
x = y
y = 42
return Private
f(33)
Comment out the assignment to y, and this works (Private.x gets 33 from y
in nested scope), with the assignment to y in place this raises NameError.
So far this is pretty much what I would have expected: you can use the
value of y from the nested scope only if y is not a local variable in the
class scope (although I would have expected an UnboundLocalError rather
than a NameError).
But, if you assign a global variable y=77 then Private.x gets 77 which
definitely seems wrong.
I knew before that nested scopes didn't seem to work quite the way I
expected with classes, but this definitely looks like a bug. Either classes
should not do nested scopes at all, or they should do them consistently
with functions.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list