getting from code object to class/function

S

Skip Montanaro

The trace module allows you to print all functions which were called at
least once during a program's run. I just checked in a change to also track
caller/callee relationships and display then at program exit.

Both types of output suffer from the fact that all the trace function gets
is the current frame. From there it can find the code object and then the
source filename and function name. There is, however, no direct way back
from the code object to (for example) the class and method which "own" that
object. I didn't see anything obvious in the inspect module that would
allow me to worm around this problem.

A not perfect solution would seem to be: if the first element of the code's
co_varnames attribute is "self" and the object in question is an instance,
work back to the class and grab the class name (which is only available
indirectly via str()), then use it to embellish the function name found in
the code object.

I'm open to other suggestions.

Thx,

Skip
 
M

Michael Hudson

Skip Montanaro said:
The trace module allows you to print all functions which were called at
least once during a program's run. I just checked in a change to also track
caller/callee relationships and display then at program exit.

Both types of output suffer from the fact that all the trace function gets
is the current frame. From there it can find the code object and then the
source filename and function name. There is, however, no direct way back
from the code object to (for example) the class and method which "own" that
object. I didn't see anything obvious in the inspect module that would
allow me to worm around this problem.

gc.get_referrers?

It's impossible in general, of course, because you can using the 'new'
module construct multiple functions that refer to the same code
object.

Cheers,
mwh
 
M

Michael Hudson

Skip Montanaro said:
mwh> gc.get_referrers?

Interesting idea.

I'm not sure it'll work though: I don't think code objects participate
in GC, so I don't know if function's traverse function call the
callback on the code object.

That said, I've just tried it, and it does work :)

Cheers,
mwh
 

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,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top