Hooking exceptions outside of call stack
Josiah Carlson
josiah.carlson at sbcglobal.net
Sat Jun 9 16:21:21 EDT 2007
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__(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
More information about the Python-list
mailing list