import, functions, and threading

Phillip J. Eby pje at telecommunity.com
Tue Mar 23 19:00:11 CET 2004


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.

If I understand this correctly, a deadlock could only occur if a lock
was being acquired by module-level code in a newly imported module,
after another thread acuired that lock, and then blocked waiting for
the import lock.

So, all this means is that you shouldn't acquire locks in module-level
code, because if you do, you can run afoul of this problem entirely
independent of whether you do any importing in functions!

So, treating this as an issue with importing inside functions seems
like a red herring.  The import lock can only be a source of deadlocks
for module-level code, and the issue applies to *any* import
statement.



More information about the Python-list mailing list