where to import

Chris Rebert clp2 at rebertia.com
Thu Feb 17 18:06:26 CET 2011

On Thu, Feb 17, 2011 at 8:44 AM, andrea crotti
<andrea.crotti.0 at gmail.com> wrote:
> Suppose I have a function which uses a few external libraries,
> and this function is only called once every 10 executions.
> Does it make sense to import these libraries for the whole module?

Yes. Having all the imports in one place keeps the code organized and
makes figuring out dependencies easier. Also, IIRC, importing
something within a function can lead to problems if threads are
Further, it's just plain conventional. PEP 8 (the Python style guide)
states: "Imports are always put at the top of the file, just after any
module comments and docstrings, and before module globals and

> import sys
> def fun():
>     import x, y, z
> Something like this is acceptable/good practice in the scenario I was
> talking about?

I would argue no, per PEP 8.

> Does it make any difference for performances too?

Yes, of course. Importing a module multiple times (as would happen if
fun() is called multiple times) is obviously slower than just
importing it once, although the 2nd and subsequent imports will be
faster as Python will just return another reference to the previously
imported instance of the module rather than importing it again from
scratch. There are also local variable vs. module-global variable
speed differences involved.

However, "Premature optimization is the root of all evil." Have you
checked whether the imports are taking a significant amount of
execution time? Odds are that they aren't. When optimizing, do so on
the basis of empirical data; run your program under a profiler, and
let the results guide your optimization process.


More information about the Python-list mailing list