import vs from module import : any performance issue?

Ivo Spam at ivonet.nl
Sat Mar 6 04:56:27 EST 2004


Quote from Dive Into Pyhton
"""
When a line of code asks for the value of a variable x, Python will search
for
that variable in all the available namespaces, in order:

 1. local namespace - specific to the current function or class method. If
the
    function defines a local variable x, or has an argument x, Python will
use
    this and stop searching.
 2. global namespace - specific to the current module. If the module has
defined
    a variable, function, or class called x, Python will use that and stop
    searching.
 3. built-in namespace - global to all modules. As a last resort, Python
will
    assume that x is the name of built-in function or variable.
"""
when you use: from x import y you import into the local namespace. so in
theory it could by a speedup to use this form. if you use import x you will
have to address the functions by there namespace (which equals the name of
x), so no speedup will be gotten there.



"Peter Otten" <__peter__ at web.de> wrote in message
news:c2c2r9$p5t$03$1 at news.t-online.com...
> 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