double import protection - how to ?

Fuzzyman fuzzyman at gmail.com
Sat Nov 29 10:44:45 EST 2008


On Nov 29, 3:40 pm, Helmut Jarausch <jarau... at skynet.be> wrote:
> Peter Otten wrote:
> > 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
>
> Thanks Steven, thanks Peter.
>
> Then it's a problem with a problem with a webserver written in Python (Karrigell-3.0)
> and probably related to multi-threading (the statements in my module get definitely
> executed more than once).
>

Python has an import lock - so multi-threaded code simultaneously
executing import statements only do the initial import once.

Michael Foord


> Thanks for your help,
> Helmut.
>
> --
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany

--
http://www.ironpythoninaction.com/



More information about the Python-list mailing list