Re: evaluating sys.exc_value

Jim Roskind (jar@infoseek.com)
Wed, 25 Jan 1995 11:47:12 -0800

> From: bshomer@ebi.ac.uk (Benny Shomer)
> Date: Wed, 25 Jan 1995 14:11:19 GMT
>
> I would like to handle an exception in the following way:
>
> Suppose I need to handle a case where a program does something with
> 'a' , let's assume a simple case - print a
>
> The problem is that sometimes a will be given to the program, and
> sometimes not. So, I could say:
>
> try:
> print a
> except NameError:
> whatever...
>
> I still want to continue the program assigning a='' so there will
> be no exception. BUT - I want this to be a general mechanism i.e.
>
> I would like to do something like:
>
> try:
> print a
> except NameError:
> eval(str(sys.exc_value) + " = ''")
>
>
> This however, fails on a SyntaxError. I tryed it with repr() as well -
> no can do...

You need to use an "exec" statement instead of "eval" function, in
order to avoid the syntax error. Eval operates on "expressions,"
which do not include "assignment statements." Exec *can* process
assignment statements (such as what you have constructed).

Having answered your question, I'd point out that this is a fairly
strange thing to be doing (IMHO), and you should use care to
understand what you will end up with. For example, since Python is a
dynamically scoped language, where were you expecting "a" to be
injected into? By default, it will (I think) appear in the current
dictionary. If you are inside a function, the exec statement would,
for instance, not inject "a" into the global dictionary. Is this what
you wanted? Why did you want to assign a ""? Why not a None? Why
not a 17? Was some other code going to access the variable after you
set it? Is that other code in the same function?

...oh well... I guess it is clear that I don't understand *why* you
are trying to do the above, perhaps you can explain further.

As another example of code that I'd expect you would want to repair
(given what you're suggesting), but I can't figure out how, consider
the following:

try:
print foo.blob
except AttributeError:
#hmm... what now. sys.exc_value is only "blob"
foo.blob = '' # but how do you make this "general" ?

It could be that you have a real cool idea in mind, so I'd like to
better understand the motivation for this sort of thing.

Jim

p.s., The exec / eval confusion/distinction is as standard part of
getting to know python ;-)

-- 
Jim Roskind
InfoSeek Corporation
voice: 408.982.4469
fax: 408.986.1889
jar@infoseek.com
----------------------------------------------------------------------------
PGP 2.6.1 Key fingerprint =  0E 2A B2 35 01 9B 5C 58  2D 52 05 9A 3D 9B 84 DB 
To get my PGP 2.6 Public Key, "finger -l jar@infoseek.com | pgp -kaf"