refactoring a group of import statements

Thomas Jollans thomas at jollans.com
Sun Jun 27 19:09:53 EDT 2010


On 06/28/2010 12:48 AM, rantingrick wrote:
> On Jun 27, 5:18 pm, Thomas Jollans <tho... at jollans.com> 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:
> 
> <snip code>
> 
>> (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?
> 
> Actually thats not always the case Thomas. There *is* a need to check
> for import exceptions *if* you don't want the script to blow chunks.
> Take for example using the Tkinter module and it's mediocre image
> support. I find that i do this sometimes...
> 
> 
> import Tkinter as tk
> try:
>     import Image #from PIL
>     print 'Using high quality images :)'
> except ImportError:
>     print 'Using low quality images :('

As such, that still appears rather useless - the following code doesn't
know how to behave ;-) Take this example from my own code: ;-)

HAVE_IMAGING = True
try:
    from PIL import Image
except ImportError:
    HAVE_IMAGING = False
    sys.stderr.write("Python Imaging Library PIL not found. Cover art
disabled.\n")

Yes, sometimes these checks are needed, because a module can enhance
your code if it's present. But that tends to be the exception rather
than the rule, and would usually require some extra code to make the
check useful in the first place, which makes a generalized for loop over
a bunch of modules appear to be of little utility

> 
> 
> Here is an example (there are other ways too) of how one might test
> multiple imports in a loop -- i'll probably get thrown to the sharks
> for this one ;-)
> 
> 
>>>> code
> Traceback (most recent call last):
>   File "<pyshell#0>", line 1, in <module>
>     code
> NameError: name 'code' is not defined
>>>> for x in 'spam', 'eggs', 'code':
> 	try:
> 		exec('import %s' %x)

Ah yes, exec. I've never liked exec - I find
globals()[x] = __import__(x)
clearer. But that might be just me.

> 	except ImportError:
> 		print 'no %s for you!' %x
> 
> no spam for you!
> no eggs for you!
>>>> code
> <module 'code' from 'C:\Python26\lib\code.pyc'>
>>>>
> 


Just to add to the head of contrived "solutions":


def _import(module, flag=None, as=None):
    try:
        if as is None: as = module
        globals()[as] = __import__(module)
        if flag is not None: globals()[flag] = True
    except ImportError:
        sys.stderr.write("%s module missing.\n" % module)
        if flag is not None: globals()[flag] = False
        else: raise

_import('x', 'HAVE_X')
_import('y', 'HAVE_Y')
_import('ZZ9PluralZAlpha', as='zz') #required

del _import # prevents me from stupidly doing this in a function



More information about the Python-list mailing list