Home > Back-end >  Check if method is from class without known string
Check if method is from class without known string

Time:07-10

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?

CodePudding user response:

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__

It actually looks like a duplicate of this.

  • Related