Import trouble

Doran_Dermot at Doran_Dermot at
Wed Dec 15 14:54:33 CET 2004

Hi Craig,

How about creating your own module that does this in

You could create a directory (Eg craig_init) and in that directory create
the file containing the following code:

try: import libxml
  # Blah, blah, blah. A clever bit of code goes here!

WARNING: I haven't checked this myself, but it appears to be the way that
the Zope Database python code has been written.  If you have the ZODB
package installed take a look at "Lib\site-packages\Btrees\".
I'm sure there must be other examples of this as well. 


-----Original Message-----
From: at
[ at] On Behalf Of
Craig Ringer
Sent: 15 December 2004 13:45
To: Frans Englich
Cc: Python mailing list
Subject: Re: Import trouble

On Wed, 2004-12-15 at 21:45, Frans Englich wrote:

> 2) I use Python modules which are not usually installed(libxml2/libxslt)
> want to fail gracefully in case the modules aren't available; print an 
> informative message. Since these imports are done in several related 
> programs, I don't want to duplicate the code, but instead centralize it.
> problem is that when I put the module imports/exception code in a
> it is as if it wasn't imported, even though there was no exceptions. I 
> suspect this is because the import is only done into the current
> the function scope(instead of file scope as I want). Is there any solution
> my problem? Or should I solve it in another way?

def import_xml:
       import libxml
   except ImportError,err:
       # handle the error
   return libxml

libxml = import_xml()

Craig Ringer


More information about the Python-list mailing list