import guards?

Peter Hansen peter at engcorp.com
Tue May 6 20:16:30 EDT 2003


Michael Mossey wrote:
> 
> Is it inefficient in Python to have something like:
> 
> myprog.py:
> -------
> 
> from mylib import *
> from math import *
> 
> mylib.py
> ------------
> 
> from math import *
> 
> Does this do the work of importing math twice?  Perhaps that is
> no big deal since it certainly won't compile math twice (or at
> all, seeing as it is a built-in, but I might create a similar
> situation with non-built-in modules).
> 
> And if this does cause it do something disk-intensive twice,
> could I put a sort of "import guard" around the import
> statements?  I'm not sure what that would look like.

1. Never optimize prematurely.  (Sorry, had to say it. :-)

2. Python doesn't actually import the module (that is, "compile
   and execute the statements at the module level") more than
   once.  Instead, after the first time it can find the name of the
   imported module already in sys.modules and basically do a 
   dict.update() on the dictionary of the importing module.  This
   is a pretty cheap operation, all things considered.

3. Try to avoid "from xxxx import *" in all but special cases.  
   Check the archives for background on this (keywords 
   "from module import" ?) but basically except in cases such as 
   (maybe) math and wxPython, it can be a very bad idea.  Definitely
   not a good habit to get into.

-Peter




More information about the Python-list mailing list