I'm trying to check if an object has a method start
and a method update
.
I thought I could use abstract base class, just like collections.abc.Iterable
work.
In my case I cannot do class Foo(Interface)
since Foo
is load dynamically, and have no access to Interface
.
What is the idiomatic way to check if an object have specific methods ?
import abc
class Interface(abc.ABC):
@abc.abstractmethod
def start():
pass
@abc.abstractmethod
def update():
pass
class Foo:
def start():
pass
def update():
pass
def main():
foo = Foo()
print(f'{isinstance(foo, Interface) = }') # False
if __name__ == '__main__':
main()
You can get all the methods of a class or class instance by doing
dir(foo)
. This will return you a list of all methods available for this class or instance. You can then check if methodsstart
andupdate
are inside this list by doing"start" in dir(foo) and "update" in dir(foo)
Note, that
dir
will also show you all of the class variables and properties, so you might not want to use it.You can read more about this topic here