Redundant importing of modules
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? -- http://mail.python.org/mailman/listinfo/python-list
Re: Redundant importing of modules
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/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Redundant importing of modules
On 21 déc, 03:03, Steve Holden wrote: > 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. (answering the OP - post didn't show off here on c.l.py): This is actually totally useless. The global namespace of a function is the namespace of the module in which it has been defined, not the namespace of the module where the function is called. -- http://mail.python.org/mailman/listinfo/python-list