Modules, namespaces, parents, and import

Dang Griffith noemail at noemail4u.com
Wed Feb 4 08:26:22 EST 2004


On Wed, 4 Feb 2004 06:28:38 -0000, "Dan Williams" <dan at ithium.net>
wrote:

>My question is thus: how do I reference a parent module and its children?
...
>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.

The flaw in your thinking is the thought that there is a parent
module.  When you have multiple C/C++ files, they are not
parent/child.  They are simply separate, perhaps sharing common
headers.  Just as in C++, one module doesn't know what other module
(or modules!) has included it.

To have a called method reference variables declared in its caller's
namespace, pass parameters instead:

------------------
# modulea
import moduleb
a = 5
moduleb.DoStuff(a)
------------------
# moduleb
import sys
def DoStuff(x):
    print x
    sys.exit(0)
------------------

The import statement is not at all like the C/C++ #include
preprocessor directive.  I'm not familiar with C++ namespaces (I
dropped out of C++ before they were added to the language), and can't
say if/how the Python import statement compares with them.

If you're looking for a way to avoid passing parameters, you can
create a third module that is used to hold your shared/global
variables:

-------------
# moda
import modb, modc

modc.variable = 27
modb.DoStuff()
-------------
# modb
import modc

def DoStuff():
    print modc.variable
-------------
# modc

variable = 0
-------------

I'm not recommending this, just mentioning it as a possibility.

    --dang



More information about the Python-list mailing list