Hooking exceptions outside of call stack

Josiah Carlson josiah.carlson at sbcglobal.net
Sat Jun 9 19:05:11 EDT 2007


Warren Stringer wrote:
> Am still trying to hook a NameError exception and continue to run. After a
> few more hours of searching the web and pouring over Martelli's book, the
> closest I've come is:
[snip]
> Is there a way of intervening as `exec cmd in globals, locals` attempts to
> translate 'c' into an object? I thought that trapping a NameError might
> work. But now, I'm not so sure.

You can always muck around with the function's globals (if the operation 
is happening inside some function...)

 >>> def foo():
...     print a
...
 >>> d = {'a':1}
 >>>
 >>> foo = type(foo)(foo.func_code, d, foo.func_name, foo.func_defaults,
foo.func_closure)
 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
 >>> foo()
1
 >>>

With a little work, you can 'merge' your namespace-like object with the 
module globals that normally exist for a function.

However, I would say again, you shouldn't be doing this kind of thing in 
production code.

  - Josiah



More information about the Python-list mailing list