refactoring a group of import statements

rantingrick rantingrick at gmail.com
Sun Jun 27 18:48:23 EDT 2010


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 :('


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)
	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'>
>>>




More information about the Python-list mailing list