Global Variable

Alex Martelli aleax at aleax.it
Tue Apr 30 10:39:48 EDT 2002


<posted & mailed>

Xiao-Qin Xia wrote:

> 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?
> 
> #---------main.py---------
> import gmpy
> import mymodule
> ...
> 
> 
> #--------mymodule.py---------
> #I want use gmpy here, do I have to import it again? can main.py add gmpy
> into a global dict?

It is by far best to import gmpy into each module that wants to use it.

This is normal Pythonic use, has negligible runtime cost (since the FIRST
import does all the work and stashes the module object snugly into
sys.modules['gmpy'], and all other imports reuse this 'cached' object),
and enhances your program's clarity considerably.

That much being said, if you've made a bet about whether it could be
done -- it can.  Your "main module" would need to do:

import gmpy
import __builtin__
__builtin__.gmpy = gmpy

"et voila".

However, don't do it.  You'll be sorry if you start messing around with
__builtin__ for any but the most pressing of emergencies.


Alex




More information about the Python-list mailing list