Global Variable

Steve Holden sholden at holdenweb.com
Tue Apr 30 08:56:49 EDT 2002


"Xiao-Qin Xia" <xx758 at cam.ac.uk> wrote in message
news:aalpqc$h9s$1 at pegasus.csx.cam.ac.uk...
> Hello,
>
> If a module (for example, gmpy) is imported in the main.py, how can it be
> used by other modules (for example, mymodule) without being imported by
> each of the other modules?
>
Let me count the ways ... but the *real* answer is, just import it into the
other modules as well! This will hardly take any time, since the code of the
module is only executed when it is first imported (or on subsequent use of
the relaod() function).

> #---------main.py---------
> import gmpy
> import mymodule
> ...
>
So, for example, you can get at gmpy in your other modules as __main__.gmpy.
Butt-ugly, isn't it?
>
> #--------mymodule.py---------
> #I want use gmpy here, do I have to import it again? can main.py add gmpy
> into a global dict?

It actually *does* add gmpy to the sys.modules dict:

>>> import sys
>>> for m in sys.modules:
...     print m
...
stat
posixpath
UserDict
signal
site
__builtin__
sys
posix
__main__
exceptions
readline
os
os.path
>>>

In practice it's much easier to say

    import mymodule

than it is to say

    import sys
    mymodule = sys.modules["mymodule"]

and there isn't even any excessive cost, so just go ahead and import the
modules you need!

A common technique for functions which aren't always going to be called is
to perform the imports inside the function. That way the import is only
performed if the function gets called, and the additional per-call imports
really don't add much overhead.

regards
 Steve
--

Steve Holden: http://www.holdenweb.com/ ; Python Web Programming:
http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list