0

Trying to check if a method is from a class. It's as simple as:

class Foo:
    def bar(self):
        return 

f = Foo()

ismethod(f.bar, Foo)  # Should evaluate to true

Syntax like hasattr(Foo(), 'bar') works if you know the method name, and the same with 'bar' in dir(Foo()); howeveer, I need to be able to pass the method object itself as the argument, not like a string as shown here. In my scenario, I need to tell if a method—passed as an argument—is of a specific class.

In other words: How do I tell if an object is a method of a class, without knowing the name of the object?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

1

You need inspect.ismethod:

import inspect


def just_func(a, b):
    return a + b

class SomeClass:
    def just_method(self, a, b, c):
        return a * b + c

obj = SomeClass()
print(inspect.ismethod(just_func)) # False
print(inspect.ismethod(obj.just_method)) # True

UPD:

Oh sorry, you need to check if it belongs to a particular class, then use:

print('SomeClass' in obj.just_method.__qualname__) # True
print('SomeClass' in just_func.__qualname__) # False

Here's what the function you want might look like:

def ismethod(func, cls):
    return cls.__name__ in func.__qualname__ and '.' in func.__qualname__

It actually looks like a duplicate of this.

QwertYou
  • 333
  • 2
  • 12
  • However, I must warn you that this method may not work correctly if the function name is a substring of the class name, such as the `AA` class and the `aAAb` function. – QwertYou Jul 18 '22 at 20:45
  • I think you are unlikely to come across such cases, but I warn you anyway – QwertYou Jul 18 '22 at 20:49
  • Although this buggy behavior can be bypassed... Yes! I have updated the answer – QwertYou Jul 18 '22 at 20:50
  • Hmm, this still doesn't work, if we have for example a `Qwert` class that has a method `aAAb` and has a class `AA`, then `ismethod(Qwert().aAAb, AA)` will return True, which is also wrong... How to fix this i don't know. – QwertYou Jul 18 '22 at 20:56