Hooking exceptions outside of call stack

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Warren Stringer

    #1

    Hooking exceptions outside of call stack

    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[b] = 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[b]=3` inside a
    try...except block because I want to enable a command line `>>>a[b]=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

  • Josiah Carlson

    #2
    Re: Hooking exceptions outside of call stack

    Warren Stringer wrote:
    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[b] = 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[b]=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__(sel f, 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

    Comment

    Working...