Importing again and again

Maric Michaud maric at aristote.info
Fri Jun 9 04:33:51 EDT 2006


Le Jeudi 08 Juin 2006 22:02, abcd a écrit :
>
> def foo():
>     import bar
>     bar.printStuff()
>
> foo()
> foo()
> foo()
> foo()
>
> ...will that re-import bar 4 times...or just import it once?  is this a
> big performance hit?

Import a module more than once doesn't execute the code of this module more 
than once.

I don't know what's your need but as some have spoke of reload I just want to 
warn you, reload a module means that you want invalidate the code of this and 
replace it by a new one, this is not like a normal but deeper import. Also, 
you'll have to deal yourself wiith references to your old code.
Hmmm,  the following example should be clear than my explanations :)

n [1]: import temp

In [2]: class a(temp.Base
temp.Base

In [2]: class a(temp.Base
temp.Base

In [2]: class a(temp.Base
temp.Base

In [2]: class a(temp.Base) : pass
   ...:

In [3]: reload(temp)
Out[3]: <module 'temp' from 'temp.pyc'>

In [4]: class b(temp.Base) : pass
   ...:

In [7]: b.__base__, a.__base__, b.__base__ is a.__base__
Out[7]: (<class 'temp.Base'>, <class 'temp.Base'>, False)

In [8]: isinstance(a(), temp.Base), isinstance(b(), temp.Base)
Out[8]: (False, True)

-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list