Import trouble

Craig Ringer craig at postnewspapers.com.au
Wed Dec 15 14:44:35 CET 2004


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

> 2) I use Python modules which are not usually installed(libxml2/libxslt) and 
> 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. The 
> problem is that when I put the module imports/exception code in a function, 
> 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 namespace: 
> the function scope(instead of file scope as I want). Is there any solution to 
> my problem? Or should I solve it in another way?

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

libxml = import_xml()


--
Craig Ringer




More information about the Python-list mailing list