refactoring a group of import statements

GrayShark howe.steven at gmail.com
Sun Jun 27 23:20:57 EDT 2010


Thanks for the help Thomas Jollans. Just what I needed. I was wondering
what the:
	__import__(name, globals={}, locals={}, fromlist=[], level=-1)

globals was (that was from the docstring on __import__. Odd, the doc on 
www.python.org has globals as a list, not a dictionary). In any case, I 
had a feeling it was the answer; I just didn't know how to do it. 

--Example test--
Python 2.6.4 (r264:75706, Jun  4 2010, 18:20:31) 
[GCC 4.4.4 20100503 (Red Hat 4.4.4-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> x = 'string'
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
>>> globals()[x] = __import__( x )
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'string', 'x']
>>> 
--ends--

That was what I was looking for. All the rest, the arguments were 
unhelpful. 

Question: If you can't answer the question, why are you talking? 

I'm American Indian. That's what I was taught. We don't talk that much. 
But you get an answer when we do talk. Makes life simpler.

Thanks you again Thomas Jollans.

GrayShark



On Mon, 28 Jun 2010 00:18:36 +0200, Thomas Jollans wrote:

> 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