Modules, namespaces, parents, and import

Dan Williams dan at ithium.net
Wed Feb 4 01:28:38 EST 2004


Hi people

I've just joined the Python list and although I'm sure my question must be
asked fairly frequently, I have been unable to find an answer after two days
of searching. For the record, my total Python experience is also two days :)
(I come from a C++ background though, so I have good programming knowledge
in general).

My question is thus: how do I reference a parent module and its children?

For instance:

main.py
-------
import sys, module1
a = 5
module1.DoStuff()

module1.py
----------
def DoStuff():
    print a
    sys.exit(0)

OK, so of course everyone is going to go "ahhhh, that won't work!" ...well,
of course not, but you can see what my intention is. The first problem is
referencing the sys module - the only way I have managed to make it work is
to import sys in module1, which is inefficient and impractical (to say
nothing of leading to awful disorganisation!). So... how do I refer to the
sys module from inside module1, when sys has been loaded inside the main
module's namespace? (e.g. parent.sys.exit(), self.parent.sys.exit(), etc.)
I'm looking for some kind of reference to parent here, and although I have
found some stuff about __dict__ and it's relatives (and some stuff about
____ but that seems discontinued) I cannot find how to do this.

So, the next thing is the variables that belong to main.py, namely a in this
case. Assuming that some kind and helpful soul points me in the right
direction by giving me a way to reference the parent namespace, can I then
access member variables in the way that seems logical...? e.g. parent.a or
self.parent.a or whatever kind of structure the referencing follows. (Yup
this one should be self-explanatory once I know how to reference the parent
module, but I just want to check :) ).

Finally, if you can see any obvious flaws with the way I am thinking about
modules, please point them out to me. I'm used to C++ headers and externs,
and PHP includes, but Python modules and packages are now to me. That said,
the basic theory seems straightforward and so long as I can reference
parents, I like the namespace implementation.

Cheers

Dan






More information about the Python-list mailing list