baffled classes within a function namespace. Evaluation order.

Bas wegwerp at gmail.com
Thu Apr 25 18:08:18 EDT 2013


On Thursday, April 25, 2013 11:27:37 PM UTC+2, Alastair Thompson wrote:
> I am completely baffled by the behavior of this code with regards to the evaluation order of namespaces when assigning the class attributes.  Both classes are nested within a function I called whywhywhy.
[snip weird namespace problem]

Hi,

I am not a namespace expert, but I think the following example shows the same problem in an easier way without any classes, and gives a more helpful error message:

In [1]: a = 123
In [2]: def f():
   ...:     print a
   ...:     b = 456

In [3]: f()
123

In [4]: def g():
   ...:     print a
   ...:     a = 456

In [5]: g()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
/home/xxx/<ipython-input-5-d65ffd94a45c> in <module>()
----> 1 g()

/home/xxx/<ipython-input-4-c304da696fc2> in g()
      1 def g():
----> 2     print a
      3     a = 456
      4 

UnboundLocalError: local variable 'a' referenced before assignment


My guess is that in f(), the compiler sees no definition of a, so it assumes is must come from the outer namespace. In g(), however, it sees on the second line that a is uses as an assignment target, so it makes the variable a local. When it is executed, it rightfully complains that the local variable is not yet defined. A smarter compiler might prevent this problem, but then again a smarter programmer would not have local and global variables with the same name.

In your example, something similar is probably happening, since you assign something to third inside example2, thereby making it 'local'. Since you are dealing with classes, the error message is probably not so clear (but whywhywhy would you define a class inside a function?) Does that make sense?

HTH,
Bas



More information about the Python-list mailing list