Retrieve class name of caller

K

Koen Van Herck

For debugging/logging purposes, I have a function

def Log(msg):
print '%s.%s: %s' % (cls, method, msg)

I call this function from a class method, and I would like to retrieve
the name of the caller method and its class. I already came up with

method = sys._getframe(1).f_code.co_name
cls = sys._getframe(1).f_locals['self'].__class__

I wonder if there are better ways to retrieve this info. In
particular, my implementation assumes that the instance parameter of
the method is called 'self', which it usually is, of course.

Regards,
Koen.
 
B

Bertrand Geston

Koen said:
For debugging/logging purposes, I have a function

def Log(msg):
print '%s.%s: %s' % (cls, method, msg)

I call this function from a class method, and I would like to retrieve
the name of the caller method and its class. I already came up with

method = sys._getframe(1).f_code.co_name
cls = sys._getframe(1).f_locals['self'].__class__

I wonder if there are better ways to retrieve this info. In
particular, my implementation assumes that the instance parameter of
the method is called 'self', which it usually is, of course.

Regards,
Koen.

Take look to the inspect module. Could be what you need (and even more).
 
K

Koen Van Herck

Bertrand Geston said:
Koen said:
For debugging/logging purposes, I have a function

def Log(msg):
print '%s.%s: %s' % (cls, method, msg)

I call this function from a class method, and I would like to retrieve
the name of the caller method and its class. I already came up with

method = sys._getframe(1).f_code.co_name
cls = sys._getframe(1).f_locals['self'].__class__

I wonder if there are better ways to retrieve this info. In
particular, my implementation assumes that the instance parameter of
the method is called 'self', which it usually is, of course.

Regards,
Koen.

Take look to the inspect module. Could be what you need (and even more).

OK. But if I have the frame or code object, how can I get the method
or function object? For example, for a method m I have code object c:

c = m.im_func.func_code

How can I find m from c ?
 

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,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top