refactoring a group of import statements
Thomas Jollans
thomas at jollans.com
Sun Jun 27 18:18:36 EDT 2010
On 06/28/2010 12:06 AM, GrayShark wrote:
> I have a large list of package files to import. I'm using a try/except
> test to verify the import. Looks like:
>
> try:
> import abc
> except ImportError:
> print( "Error importing abc" )
>
> I've got many of those segments. I want to try and refactor this part
> of the code.
>
> Trying:
> for mod in ['ab', 'cd', 'ef' ]:
> try:
> mod = __import__( mod )
> except ImportError:
> print( "Error importing %" % mod )
>
> This of course doesn't work. The module ab get's assign in the application
> as mod.
>
> Tried:
> for mod in ['ab', 'cd', 'ef' ]:
> ('%s' % mod ) = __import__( mod )
>
> Still no joy.
>
> I need a way to deference the the string in mod to be just a variable.
>
> Any suggestions?
(1) Don't. If you need the module, there's no reason to check for
exceptions. Just let the ImportError propagate. Okay, maybe you don't
actually need the module - then why do you have to import it in the
first place?
(2) globals()[mod] = __import__(mod)
(3) Why not
try:
import x
import y
import z
except ImportError as exc:
display_error_properly(exc)
raise exc
-- Thomas
More information about the Python-list
mailing list