In Python, how can you get the name of a member function's class?
Asked Answered
P

5

20

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

testFunc.__class__ 

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

Partheniaparthenocarpy answered 20/11, 2008 at 16:30 Comment(0)
D
14
testFunc.im_class

https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

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

Danzig answered 20/11, 2008 at 16:42 Comment(3)
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!Danzig
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. +1Clinkstone
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: <#306630>Partheniaparthenocarpy
J
36

From python 3.3, .im_class is gone. You can use .__qualname__ instead. Here is the corresponding PEP: https://www.python.org/dev/peps/pep-3155/

class C:
    def f(): pass
    class D:
        def g(): pass

print(C.__qualname__) # 'C'
print(C.f.__qualname__) # 'C.f'
print(C.D.__qualname__) #'C.D'
print(C.D.g.__qualname__) #'C.D.g'

With nested functions:

def f():
    def g():
        pass
    return g

f.__qualname__  # 'f'
f().__qualname__  # 'f.<locals>.g'
Juxon answered 3/12, 2016 at 22:12 Comment(0)
D
14
testFunc.im_class

https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

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

Danzig answered 20/11, 2008 at 16:42 Comment(3)
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!Danzig
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. +1Clinkstone
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: <#306630>Partheniaparthenocarpy
P
8

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

testFunc.__self__.__class__

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:

testFunc.__objclass__

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
Type "help", "copyright", "credits" or "license" for more information.
>>> 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):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
>>> hd2.im_class
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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.

Pasargadae answered 20/11, 2008 at 16:35 Comment(2)
No, that gives you the message: "AttributeError: 'function' object has no attribute 'self'".Partheniaparthenocarpy
Try the objclass attribute and see if that works. If it does, then your function is unbound.Pasargadae
C
3

instance methods will have attributes .im_class .im_func .im_self

http://docs.python.org/library/inspect.html#types-and-members

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

Clinkstone answered 20/11, 2008 at 16:53 Comment(0)
A
0

Please use following function to get method names inside of a class

def getLocalMethods(clss):
import types
# This is a helper function for the test function below.
# It returns a sorted list of the names of the methods
# defined in a class. It's okay if you don't fully understand it!
result = [ ]
for var in clss.__dict__:
    val = clss.__dict__[var]
    if (isinstance(val, types.FunctionType)):
        result.append(var)
return sorted(result)
Anabel answered 2/3, 2020 at 21:12 Comment(1)
This doesn't actually answer the question, which was about finding the name of the class from inside the method, not finding the names of the methods.Lightheaded

© 2022 - 2024 — McMap. All rights reserved.