From: GrayShark on
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?

GrayShark

From: Thomas Jollans on
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
From: rantingrick on
On Jun 27, 5:18 pm, Thomas Jollans <tho...(a)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'>
>>>

From: Thomas Jollans on
On 06/28/2010 12:48 AM, rantingrick wrote:
> On Jun 27, 5:18 pm, Thomas Jollans <tho...(a)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
From: rantingrick on
On Jun 27, 6:09 pm, Thomas Jollans <tho...(a)jollans.com> wrote:

> > 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: ;-)

Ah yes that was me trying to save a little server space by not posting
my whole script. So Yes I did leave a little "mystery" for the
advanced reader to dissect. *wink*

> 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

agreed! However i was going to let the OP find this out though his own
realization and in the meantime show him the power of eval/exec even
if it could blow a pinky toe off ;-).

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

What's the irrational fear/hatred some have of eval and exec? You *do*
know that harnessing these facilities simply invokes an underlying
process that the interpretor itself uses every time you import or run
a script. So if you fear eval/exec you *really* should fear the Python
interpretor *gasp*! Does that seem logical? Really don't fear eval/
exec! No, fear the while loop as it's much more apt to breaking loose
and running amuck!