Where to place imports
John [H2O]
washakie at gmail.com
Fri Jan 23 12:08:22 EST 2009
So it isn't inefficient to import a bunch of modules that may not be used,
say if only one function is used that doesn't rely on a larger module like
numpy or pylab?
Thanks.
Diez B. Roggisch-2 wrote:
>
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
View this message in context: http://www.nabble.com/Where-to-place-imports-tp21627895p21628590.html
Sent from the Python - python-list mailing list archive at Nabble.com.
More information about the Python-list
mailing list