Hooking exceptions outside of call stack

  • Thread starter Warren Stringer
  • Start date
W

Warren Stringer

Here is what I would like to do:

#------------------------------------------------------------
a = Tr3() # implements domain specific language
a.b = 1 # this works, Tr3 overrides __getattr__
a.__dict__['b'] = 2 # just so you know that b is local
a = 3 # I want to resolve locally, but get:

Traceback (most recent call last): ...
exec cmd in globals, locals ...
NameError: global name 'b' is not defined
#------------------------------------------------------------

So far, I've tried capturing exceptions in __getattr__, __setitem__, and
__setattr__, with no luck. I do NOT want to put `a=3` inside a
try...except block because I want to enable a command line `>>>a=3`

Is there a way to hook a NameError exception outside of the call stack?
Perhaps, inside Tr3.__init__ ? Is there a way of putting back unhandled
NameError exceptions, so that they unwind the stack normally?

This is intended for production code.

Many thanks!

Warren
 
J

Josiah Carlson

Warren said:
Here is what I would like to do:

#------------------------------------------------------------
a = Tr3() # implements domain specific language
a.b = 1 # this works, Tr3 overrides __getattr__
a.__dict__['b'] = 2 # just so you know that b is local
a = 3 # I want to resolve locally, but get:

Traceback (most recent call last): ...
exec cmd in globals, locals ...
NameError: global name 'b' is not defined
#------------------------------------------------------------


Note that your a=3 is the same as '__ = b;a[__]=3' You get that
exception because b is not a bound name in the namespace you are
currently using. In order to get what you want, you will either need to
use a['b'] = 3, a.b = 3, or a method that I refuse to describe to you.
This is intended for production code.

The reason I refuse to describe to you the method that could 'solve'
your particular problem is because it would be very difficult to
differentiate between what you *want* to happen, and actual errors,
which would make production code *very* difficult to get right.

As an alternative to a['b'], you could use a[Z.b], for an object Z:

class Z:
def __getattr__(self, a):
return a

Z = Z()

Which will have much less potential for destroying the maintainability
and testability of your production code than hooking any trace function.


- Josiah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top