Typing interfaces
You could use a typing.Union
but, it sounds like you really want structural typing not nominal. Python supports this using typing.Protocol
, which is a supported part of the python type-hinting system, so mypy
will understand it, for example:
import typing
class Fooable(typing.Protocol):
def foo(self) -> int:
...
class One(object):
def foo(self) -> int:
return 42
class Two(object):
def foo(self) -> int:
return 142
def factory(a: str) -> Fooable:
if a == "one":
return One()
return Two()
x = factory('one')
x.foo()
Note, structural typing fits well with Python's duck-typing ethos. Python's typing system supports both structural and nominal forms.