A scoping question
Steven Bethard
steven.bethard at gmail.com
Tue Dec 28 15:11:20 EST 2004
It's me wrote:
> This must be another newbie gotchas.
>
> Consider the following silly code, let say I have the following in file1.py:
>
> #=============
> import file2
> global myBaseClass
> myBaseClass = file2.BaseClass()
> myBaseClass.AddChild(file2.NextClass())
> #=============
>
> and in file2.py, I have:
>
> #=============
> global myBaseClass
> class BaseClass:
> def __init__(self):
> self.MyChilds = []
> ...
> def AddChild(NewChild):
> self.MyChilds.append(NewChild)
> ...
> class NextClass:
> def __init__(self):
> for eachChild in myBaseClass.MyChilds: # <- ERROR
> ...
> #=============
>
> When I run this, Python complains that myBaseClass is undefined in the last
> line above.
>
> What am I doing wrong? (Yes, I know I am thinking too much in C). I
> thought the global declaration would have been sufficient but it's obviously
> not.
I think you're confused about what the global keword does. Declaring a
name as global makes that name global *to the module*:
http://docs.python.org/ref/global.html
http://docs.python.org/lib/built-in-funcs.html#l2h-32
What you probably want instead is:
-------------------- file1.py --------------------
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
--------------------------------------------------
-------------------- file2.py --------------------
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self):
from file1 import myBaseClass # IMPORT
for eachChild in myBaseClass.MyChilds:
pass
--------------------------------------------------
Note that I import myBaseClass in __init__. If I imported it at the top
of the module, then file1 would import file2 which would then import
file1 and you'd have a circular dependency.
As it is, your code is very tightly coupled. Why don't you put all this
code into a single module?
Steve
More information about the Python-list
mailing list