isinstance and abstract base class

340 views Asked by At

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()

1

There are 1 answers

0
wikwoj On

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 methods start and update 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