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
(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
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
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
Its so strange when I agree with you. Like, the universe seems out of
alignment.
But yes. What he said.
We aren't necessarily going to just answer a direct question with a
direct answer, because *very often* the answer might depend on more then
what you're saying, or the question doesn't seem to make sense the way
posed (even if the answer is obvious to us, we may go, 'but wait, why
would you ask this?' and try to find a deeper understanding to help you
more), or we have experience with people asking the very same sort of
question and they're going down a path leading to pain and suffering.
So we will advise and share our experience in addition to, perhaps
eventually, answering directly.
If you don't like it, tough :)
--
... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
Look, I'm not American Indian, though I question how many American Indians
call themselves American Indians. *But* in keeping with the true spirit of
what this python list is all about (i.e., finding new ways to aggravate
people), I refer you all to the immortal words of Tom Lehrer:
One week of every year is designated National Brotherhood Week. This is just
one of many such weeks honoring various worthy causes. One of my favorites is
National Make-fun-of-the-handicapped Week which Frank Fontaine and Jerry Lewis
are in charge of as you know. During National Brotherhood Week various special
events are arranged to drive home the message of brotherhood. This year, for
example, on the first day of the week Malcolm X was killed which gives you an
idea of how effective the whole thing is. I'm sure we all agree that we ought
to love one another and I know there are people in the world that do not love
their fellow human beings and I hate people like that. Here's a song about
National Brotherhood Week.
Oh, the white folks hate the black folks,
And the black folks hate the white folks.
To hate all but the right folks
Is an old established rule.
But during National Brotherhood Week, National Brotherhood Week,
Lena Horne and Sheriff Clarke are dancing cheek to cheek.
It's fun to eulogize
The people you despise,
As long as you don't let 'em in your school.
Oh, the poor folks hate the rich folks,
And the rich folks hate the poor folks.
All of my folks hate all of your folks,
It's American as apple pie.
But during National Brotherhood Week, National Brotherhood Week,
New Yorkers love the Puerto Ricans 'cause it's very chic.
Step up and shake the hand
Of someone you can't stand.
You can tolerate him if you try.
Oh, the Protestants hate the Catholics,
And the Catholics hate the Protestants,
And the Hindus hate the Muslims,
And everybody hates the Jews.
But during National Brotherhood Week, National Brotherhood Week,
It's National Everyone-smile-at-one-another-hood Week.
Be nice to people who
Are inferior to you.
It's only for a week, so have no fear.
Be grateful that it doesn't last all year!
http://www.youtube.com/watch?v=dUwbZ9AlSPI
--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Why not? Because that destroys the original traceback. Inside an
except clause, you should almost always use a bare raise. (I'm not
absolutely certain that the new "as" subclause doesn't fix the problem,
but why not stick with an idiom guaranteed to work in all versions of
Python.)
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/
"If you don't know what your program is supposed to do, you'd better not
start writing it." --Dijkstra