Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

refactoring a group of import statements

12 views
Skip to first unread message

GrayShark

unread,
Jun 27, 2010, 6:06:20 PM6/27/10
to
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

Thomas Jollans

unread,
Jun 27, 2010, 6:18:36 PM6/27/10
to pytho...@python.org

(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

Message has been deleted

Thomas Jollans

unread,
Jun 27, 2010, 7:09:53 PM6/27/10
to pytho...@python.org
On 06/28/2010 12:48 AM, rantingrick wrote:

> On Jun 27, 5:18 pm, Thomas Jollans <tho...@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

Message has been deleted

GrayShark

unread,
Jun 27, 2010, 11:20:57 PM6/27/10
to
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

Message has been deleted

Stephen Hansen

unread,
Jun 28, 2010, 4:09:32 PM6/28/10
to pytho...@python.org
On 6/28/10 12:54 PM, rantingrick wrote:

> On Jun 27, 10:20 pm, GrayShark<howe.ste...@gmail.com> wrote:
>> Question: If you can't answer the question, why are you talking?
>
> Q: If you can't take advice without complaining, then why are you
> asking?

>
>> 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.
>
> Yes thats about as intelligent as me saying... "I'm an American
> sprinter. We don't walk that much. But we move faster when we run.
> Makes winning easier.
>
> Yes, apparently it is *NOT* wise to "swim with sharks"!
>
> GrayShark, this is the second time i've seen you spit on those
> offering help. Whether or not my help was helpful to you does not
> matter. You're only going to thin the "pool" of answers by resorting
> to such childish behaviors. If you don't think an answer was helpful
> to you, just ignore it and move on. But i'm probably wasting my time
> again helping you so...

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/

Steven W. Orr

unread,
Jun 28, 2010, 10:31:40 PM6/28/10
to python list
On 06/27/10 23:20, quoth GrayShark:
> Thanks for the help

> 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.
>

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

signature.asc

Aahz

unread,
Jun 29, 2010, 3:45:28 PM6/29/10
to
In article <mailman.2202.1277677...@python.org>,

Thomas Jollans <tho...@jollans.com> wrote:
>
>(3) Why not
>
>try:
> import x
> import y
> import z
>except ImportError as exc:
> display_error_properly(exc)
> raise exc

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

0 new messages