double import protection - how to ?

Peter Otten __peter__ at web.de
Sat Nov 29 08:00:24 EST 2008


Helmut Jarausch wrote:

> I have a module which gets imported at several different places
> not all of which are under my control.
> 
> How can I achieve that  all/some statements within that module
> get executed only at the very first import?

What you describe is Python's default behaviour. A module is executed once
and then cached in sys.modules. The second import is then just a cache
lookup. 

This may only fail if a module is imported under different names, typically
when you have directory  in sys.path that is part of a package, or when you
import the main script.

Peter



More information about the Python-list mailing list