What is the correct way to type an "interface" in python 3?
In the following sample:
class One(object):
def foo(self) -> int:
return 42
class Two(object):
def foo(self) -> int:
return 142
def factory(a: str):
if a == "one":
return One()
return Two()
what would be the correct way to type the return value of the factory
function?
It should be something like "A type with a single method named foo
that accepts no arguments and returns an integer".
But not sure I can find how to do that.
UPD: this question is exclusively dedicated to typing.
Interfaces are typesAn interface is a type in Java. It specifies which objects can be used as values of which variables or parameters. An interface lists the methods that objects implementing the interface have, giving each method's signature (name, parameter types, and return type).
TypeScript Interface TypeTypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.
Interfaces are basically a way to describe data shapes, for example, an object. Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type.
Interfaces are capable of describing the wide range of shapes that JavaScript objects can take. In addition to describing an object with properties, interfaces are also capable of describing function types. To describe a function type with an interface, we give the interface a call signature.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With