Nested scopes and class variables

Dave Benjamin ramen at
Mon Jan 31 01:57:50 EST 2005

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)

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

Any implementation gurus have some insight into what's going on here?

 .:[ dave benjamin: ramen/[sp00] -:- -:- ]:.
        "talking about music is like dancing about architecture."

More information about the Python-list mailing list