import vs from module import : any performance issue?

Peter Otten __peter__ at web.de
Sat Mar 6 03:41:12 EST 2004


Pierre Rouleau wrote:

> Q1:
> I'v seen mentionned in some post that there could be performance issues
> of using:
> 
> from moduleX import whatever
> 
> as opposed to:
> 
> import moduleX
> 
> What would be the performance issues?

You wouldn't put the import statement into an inner loop, so why bother.
Every module is imported once (there is a pathological exception) and
subsequent imports are essentially lookups in sys.modules.
However, moduleX.whatever() is one dictionary lookup slower than the bare 
whatever(), and *that* might occur in an inner loop.

> 
> Q2:
> What happens when names from moduleX are imported using the first former
> syntax in some modules of an application and imported using the latter
> syntax in other modules of the same application?

Nothing. You can even mix both forms in the same module:

>>> import os
>>> from os import walk
>>> os.walk
<function walk at 0x40279a74>
>>> walk
<function walk at 0x40279a74>
>>>

> Q3:
> It's my understanding that using the "from moduleX import whatever"
> syntax in moduleA, all of moduleX code will run and only the name
> "whatever" will be made available to moduleA.  What are the benefit of
> using this syntax then, is it only the fact that you don't have to type
> the "moduleX." prefix in moduleA?

A tiny speedup. The disadvantage being pollution of the importing module's
namespace. Not as bad as from module import *, though.

Peter



More information about the Python-list mailing list