Take the 2-minute tour ×

I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.

def analyser(testFunc):
    print testFunc.__name__, 'belongs to the class, ...

I thought


would solve my problems, but that just tells me that testFunc is a function.

share|improve this question
add comment

3 Answers

up vote 9 down vote accepted


im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods

share|improve this answer
tip: when you have such a problem, you can use "dir" in your interpreter to see which method testFunc has, or better: ipython tab completion helps! –  Piotr Lesnicki Nov 20 '08 at 16:45
I'm always a moment too late on my reponses. I just couldn't seem to locate that User-defined methods stanza in the new docs. +1 –  JimB Nov 20 '08 at 17:23
Thanks; your solution works fine for the example I gave. Unfortunately for me I had simplified my actual problem too much. I have raised this in another question: <stackoverflow.com/questions/306130/…; –  Charles Anderson Nov 20 '08 at 17:29
add comment

I'm not a Python expert, but does this work?


It seems to work for bound methods, but in your case, you may be using an unbound method, in which case this may work better:


Here's the test I used:

Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
>>> import hashlib
>>> hd = hashlib.md5().hexdigest
>>> hd
<built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>
>>> hd.__self__.__class__
<type '_hashlib.HASH'>
>>> hd2 = hd.__self__.__class__.hexdigest
>>> hd2
<method 'hexdigest' of '_hashlib.HASH' objects>
>>> hd2.__objclass__
<type '_hashlib.HASH'>

Oh yes, another thing:

>>> hd.im_class
Traceback (most recent call last):
AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
>>> hd2.im_class
Traceback (most recent call last):
AttributeError: 'method_descriptor' object has no attribute 'im_class'

So if you want something bulletproof, it should handle __objclass__ and __self__ too. But your mileage may vary.

share|improve this answer
No, that gives you the message: "AttributeError: 'function' object has no attribute 'self'". –  Charles Anderson Nov 20 '08 at 16:39
Try the objclass attribute and see if that works. If it does, then your function is unbound. –  Chris Jester-Young Nov 20 '08 at 16:43
add comment

instance methods will have attributes .im_class .im_func .im_self


You probably want to see if the function hasattr .im_class, and get the class info from there.

share|improve this answer
add comment

Your Answer


