M
mrstevegross
I ran into a weird behavior with lexical scope in Python. I'm hoping
someone on this forum can explain it to me.
Here's the situation: I have an Outer class. In the Outer class, I
define a nested class 'Inner' with a simple constructor. Outer's
constructor creates an instance of Inner. The code looks like this:
=========
class Outer:
class Inner:
def __init__(self):
pass
def __init__ (self):
a = Inner()
Outer()
=========
However, the above code doesn't work. The creation of Inner() fails.
The error message looks like this:
File "/tmp/foo.py", line 12, in <module>
Outer()
File "/tmp/foo.py", line 10, in __init__
a = Inner()
NameError: global name 'Inner' is not defined
This surprises me! Since the construction of Inner takes place within
the lexical scope 'Outer', I assumed the interpreter would search the
Outer scope and find the 'Inner' symbol. But it doesn't! If I change:
a = Inner()
to
a = Outer.Inner()
it works fine, though.
So, can anyone explain to me how Python looks up symbols? It doesn't
seem to be searching the scopes I expected...
Thanks,
--Steve
someone on this forum can explain it to me.
Here's the situation: I have an Outer class. In the Outer class, I
define a nested class 'Inner' with a simple constructor. Outer's
constructor creates an instance of Inner. The code looks like this:
=========
class Outer:
class Inner:
def __init__(self):
pass
def __init__ (self):
a = Inner()
Outer()
=========
However, the above code doesn't work. The creation of Inner() fails.
The error message looks like this:
File "/tmp/foo.py", line 12, in <module>
Outer()
File "/tmp/foo.py", line 10, in __init__
a = Inner()
NameError: global name 'Inner' is not defined
This surprises me! Since the construction of Inner takes place within
the lexical scope 'Outer', I assumed the interpreter would search the
Outer scope and find the 'Inner' symbol. But it doesn't! If I change:
a = Inner()
to
a = Outer.Inner()
it works fine, though.
So, can anyone explain to me how Python looks up symbols? It doesn't
seem to be searching the scopes I expected...
Thanks,
--Steve