RedBlog

On technology, politics and life

Entries tagged "scope".

Out of scope

2008-10-03

Python 2.3 introduced scoping, just like LISP and other real languages - variables in a surrounding scope can be accessed from an inner scope. Even the function being defined can be accessed from an inner scope.

Class definitions are sort of like scopes:

>>> class A(object):
...  foo = 33
...  bar = foo
... 
>>> A.bar
33

but not entierly...

>>> class X:
...  def foo(self):
...   return foo
... 
>>> X().foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in foo
NameError: global name 'foo' is not defined
>>> def foo():
...  return foo
... 
>>> foo()
<function foo at 0x4095c5a4>

This can seem benign, since you rarely would want the function foo, but rather the method wrapper of foo, which is accessible through self.foo. However, this causes a sever problem when nesting classes:

>>> class X(object):
...  class Y(object): pass
...  class Y2(Y): pass
...
>>> class X(object):
...  class Y(object):
...   class Z(object): pass
...  class Y2(Y):
...   class Z(Y.Z): pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in X
  File "<stdin>", line 5, in Y2
NameError: name 'Y' is not defined
Tags: bugs, functions, languages, methods, python, scope.
link:http://redhog.org/Blog/Out_of_scope.html approved:1 Comments in other blogs

RSS Feed