3

For my exception class I'd like to find out whether the function which instantiated the exception object is a method and if so, show the class name.

So in the init method of my exception class I get the name of the calling function:

frame, module, line, function, context, index = inspect.stack()[1]

But is there any way the get the class name (if any) of the calling function?

  • 2
    Similar question: [how to retrieve class information from a frame object](http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object). The accepted answer there should provide a good starting point. – samplebias May 02 '11 at 23:40

1 Answers1

2

Assuming the frame is for an instance method:

self_argument = frame.f_code.co_varnames[0]  # This *should* be 'self'.
instance = frame.f_locals[self_argument]
class_name = instance.__class__.__name__
Ian B.
  • 243
  • 1
  • 6
  • It's very difficult to determine whether a given code object is in an instance method, though. – kindall May 03 '11 at 00:02
  • How so? Since you already have the presumed instance object and the name of the instance method, you could always ensure that the parameter named `self` is what it claims to by checking with `hasattr` for the presence of the method. – Ian B. May 03 '11 at 03:12
  • 1
    Well, first, `self` is just a convention. Second, you're not actually checking the name of the first argument to make sure it's "self." Third, you can have an instance method function whose first argument is not `self` using a decorator. Fourth, to be sure, you'd need to do more than check for the existence of an attribute with the correct name, you'd want to make sure it at east had the same code object in it. Even that doesn't make it 100% sure, but it might be good enough for most cases. Oh yeah, the attribute name isn't necessarily the same as the function name. :-) – kindall May 03 '11 at 04:30