1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python type hint: Intersection of types (class implementing interface)

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I have a python class defining an interface

    class InterfaceFoo:
    pass


    some abstract class

    class AbstractBar:
    pass


    and perhaps a concrete class

    class Bar(InterfaceFoo):
    pass


    implementing my interface (or, if you wish, both the interfaces Interface Foo and AbstractBar).

    Now in some situations, I would like to have a type hint saying »I expect an instance of a class that is derived from AbstractBar and implements InterfaceFoo«. How can I do this in Python? Of course, I could go through my code and add all possible concrete classes that are subclasses of AbstractBar and implement InterfaceFoo but I think that's a very ugly solution.

    def func(obj: AbstractBar implementing InterfaceFoo):
    pass


    This is possible in other languages, e.g. Objective-C, where you can write BaseClass<Interface>. I'm wondering, if there is an analogue in Python to this?

    Continue reading...

Compartilhe esta Página