Redundant importing of modules

Steve Holden steve at holdenweb.com
Mon Dec 20 21:03:45 EST 2010


On 12/20/2010 8:36 PM, Jshgwave wrote:
> When writing a function that uses a module such as NumPy, it is tempting
> to include the statement "import numpy" or "import numpy as np" in the
> definition of the function, in case the  function is used in a script
> that hasn't already imported NumPy.
> 
> That could lead to the script issuing the "import numpy" command more
> than once.
> 
> Does Python know to disregard redundant "import" commands?
> 
Oh, yes (as long as they are imported by the same name each time).

There's a dict at sys.modules that has a key for each loaded module's
name. When an attempt is made to import a module the first thing the
interpreter does is to look at sys.modules. If it has the correct key in
it then the assumption is that the module has already been imported, and
its namespace is made available as the module name immediately.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list