[Python-Dev] Fix import errors to have data (original) (raw)
Jim Fulton jim at zope.com
Tue Jul 27 14:52:22 CEST 2004
- Previous message: [Python-Dev] MSI Documentation
- Next message: [Python-Dev] Fix import errors to have data
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
A common idiom to optionally support some module if it is present is to use ImportError handlers:
try: import foo except ImportError: # Configure for absense of foo ... else: # Configure for presense of foo ...
Unfortunately, this is a bug trap. The module foo might be present and yet it's import could fail with an import error. This can happen if one of its imports fails. Code like that above will hide such bugs.
Unfortunately, it's hard to do this correctly, because ImportErrors don't have the module name as data. When the import error is raised, it is raised with an error message rather than data. This is because most standard exception classes share a common str that simply prints their initialization arguments.
At present, to conditionally support a module, you have to use code like:
try: import foo except ImportError, v: if not str(v).endsswith(' foo'): raise # Configure for absense of foo ... else: # Configure for presense of foo ...
which is ugly and brittle.
I'd like to get this fixed.
I propose to:
Provide ImportError with an init that takes a module name and sets a module_name attribute
Provide ImportError with an str that produces the message we have now
Change standard code that raises import errors to provide just the module name.
With this change, one could write careful conditional import code like this:
try: import foo except ImportError, v: if v.module_name != 'foo': raise # Configure for absense of foo ... else: # Configure for presense of foo ...
which is much cleaner IMO.
Jim
-- Jim Fulton mailto:jim at zope.com Python Powered! CTO (540) 361-1714 http://www.python.org Zope Corporation http://www.zope.com http://www.zope.org
- Previous message: [Python-Dev] MSI Documentation
- Next message: [Python-Dev] Fix import errors to have data
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]