[Q] Namespaces

s713221 at student.gu.edu.au s713221 at student.gu.edu.au
Tue May 29 05:31:08 EDT 2001


Siew-Ann Cheong wrote:
> 
> Hi,
> 
> I noticed the following:
> 
> If I have moduleA.py and moduleB.py, such that the functions defined in
> moduleB uses those defined in moduleA, an "import moduleA" statement is
> necessary in moduleB.py.
> 
> If now moduleB is imported into the interpreter, moduleA functions appear
> in the namespace of moduleB.
> 
> There are situations where moduleA itself will be imported directly, but
> this appears under the __main__ namespace.
> 
> My question is: is it possible to perform some sort of check for existing
> moduleA functions when importing moduleB, and import moduleA either into
> the main namespace or the moduleB namespace only when moduleA has not been
> loaded?  Something like the #ifndef preprocessor statements in C/C++?
> 
> Thanks!
> 
> Cheong Siew Ann

There really isn't much point. The import moduleA statement returns a
reference to the one instance of moduleA, so when you import into the
main namespace and the module namespace, there's little cost in terms of
memory. Trying to import into one is only going to save an amount of
memory equivalent to one reference, which is tiny.
In addition, I think there'd be some trouble with trying to allow
moduleB access to the global moduleA functions. If anyone can tell me a
workaround, that would be appreciated,

[joal at bb408 joal]$ echo "print sys.path" > test.py

[joal at bb408 joal]$ python2

Python 2.1 (#1, Apr 22 2001, 13:28:57)
[GCC 2.95.3 19991030 (prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import sys
>>> import test
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "test.py", line 1, in ?
    print sys.path
NameError: name 'sys' is not defined
>>>

[joal at bb408 joal]$ echo "global sys; print sys.path" > test.py

[joal at bb408 joal]$ python2

Python 2.1 (#1, Apr 22 2001, 13:28:57)
[GCC 2.95.3 19991030 (prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import sys
>>> import test
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "test.py", line 1, in ?
    global sys; print sys.path
NameError: global name 'sys' is not defined 

Joal Heagney/AncientHart



More information about the Python-list mailing list