Nested scopes and class variables
From: Dave Benjamin (ramen_at_lackingtalent.com)
Date: 01/31/05
- Next message: Fredrik Lundh: "Re: a Python bug in processing __del__ method ??"
- Previous message: Bryan: "Re: Regarding exception handling"
- Next in thread: wittempj_at_hotmail.com: "Re: Nested scopes and class variables"
- Reply: wittempj_at_hotmail.com: "Re: Nested scopes and class variables"
- Reply: Nick Coghlan: "Re: Nested scopes and class variables"
- Reply: Alex Martelli: "Re: Nested scopes and class variables"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 31 Jan 2005 06:57:50 -0000
I ran into an odd little edge case while experimenting with functions that
create classes on the fly (don't ask me why):
>>> def f(x):
... class C(object):
... x = x
... print C.x
...
>>> f(5)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
File "<stdin>", line 3, in C
NameError: name 'x' is not defined
"x" clearly is defined, but apparently Python is not looking at the nested
variable scope to find it. What's stranger is that if I rename the parameter
"x" to "y", the error goes away:
>>> def f(y):
... class C(object):
... x = y
... print C.x
...
>>> f(5)
5
So, it's not like nested scopes aren't supported in the class block. Rather,
when it sees "x = x", it seems like Python is determining at that point that
"x" is a class variable, and refuses to search any further.
At the top-level, it works as expected:
>>> x = 5
>>> class C(object):
... x = x
...
>>> C.x
5
Any implementation gurus have some insight into what's going on here?
--
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
- Next message: Fredrik Lundh: "Re: a Python bug in processing __del__ method ??"
- Previous message: Bryan: "Re: Regarding exception handling"
- Next in thread: wittempj_at_hotmail.com: "Re: Nested scopes and class variables"
- Reply: wittempj_at_hotmail.com: "Re: Nested scopes and class variables"
- Reply: Nick Coghlan: "Re: Nested scopes and class variables"
- Reply: Alex Martelli: "Re: Nested scopes and class variables"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]