import, functions, and threading

Aahz aahz at pythoncraft.com
Mon Mar 15 19:54:03 CET 2004


In article <359f85cd.0403141151.1546b5d0 at posting.google.com>,
Ian Bicking <ianb at colorstudy.com> wrote:
>aahz at pythoncraft.com (Aahz) wrote in message news:<c2rkgj$irh$1 at panix2.panix.com>...
>>
>> There were some posts recently discussing whether it's poor style to put
>> import statements inside functions.  I recently got reminded that there's
>> one very good reason to avoid it: Python has an import lock that blocks
>> more than one thread from executing import statements.  Putting import
>> statements inside functions that might be called in a threaded
>> environment is asking for deadlock trouble.
>
>Just saw this on the week Python URL... anyway, an alternative that
>should be safer:
>
>somemodule = None
>
>def whatever():
>    global somemodule
>    if somemodule is None:
>        import somemodule
>
>I'm still not sure if it's entirely safe in all cases, but I think it
>is...?  Anyway, it allows for lazy loading.

Enh.  You've got an idea, but your implementation probably still has a
race condition.  And you're breaking "simple is better than complex".
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"usenet imitates usenet"  --Darkhawk



More information about the Python-list mailing list