andrew cooke wrote:
This is a bit vague, I'm afraid, but is there any way for me to take
code like:

   a = Foo()
   beta = Bar()

and somehow attach the string "a" to the Foo instance and "beta" to
the Bar instance.  At some later point in the program I want to be
able to look at the Bar instance and say to the user "this was called
beta in your routine".

The motivation is debugging an embedded domain specific language and
the solution has to be cross platform for Python 3+ (bonus points for
Python 2 too).

Obviously I can parse the code, but I was wondering if there was some
other (no doubt terribly hacky) approach.  Even some idea of what to
google for would be a help...

Thanks,
Andrew

This comes up periodically in this list, and the answer is always something like: you can't get there from here. As you have noticed, it can't be done in the __init__() of the object, since the symbol it'll be bound to doesn't generally exist yet, and even if it does, there's no way to know which one it is.

You could write a function that the user could voluntarily call at the end of his function, that would find all symbols of a specified kind, and store the kind of information you're asking about. But of course, some class instances should not be added to, and some cannot. So you'd need some form of filter to indicate which ones to do.

In the sample below, I'll assume you want to do this for all classes derived from Mybase.

(untested):

def label_stuff(symbols):
   for symbol in symbols:
       if  isinstance(symbols[symbol], Mybase):
           symbols[symbol].bind_name = symbol

And the user would simply make a call at the end of each such function, like:

def   my_func():
     a = ...
     b = ...
     label_stuff(locals)


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to