Where to place imports

Diez B. Roggisch deets at nospam.web.de
Fri Jan 23 11:48:19 EST 2009


John [H2O] schrieb:
> Hello, Im writing some modules and I am a little confused about where to
> place my imports...
> 
> I don't really do any class programming yet, just defining a bunch of
> functions, so presently I have something along the lines of:
> 
> import sys
> import os
> import traceback
> 
> 
> def Foo1(a,b):
>    import numpy
>    import datetime
>    return c
> 
> def Foo2(a,b):
>    import datetime
> 
>    c = Foo1(a,b)
>    return c
> 
> etc...
> 
> Above obviously just for the form, but the point is, in some cases I may
> import modules twice, but other times I may not use them at all, so should I
> import everything into the main module? Or individually import them into
> functions. Is there a performance penalty either way? 

Usually, you should import on the top of the module. That's the cleanest 
way, and the most performant one.

There is a small performance penalty when doing it inside functions - 
but not too much. It boils down to a lookup if the imported module has 
already been imported before.


The only valid reason for doing imports inside functions is if you 
otherwise get into circular dependency hell, or have modules that need 
some manipulation of the sys.path before they actually can be imported. 
This is never true for system modules, and certainly to avoid if possible.

Diez



More information about the Python-list mailing list