Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing interfaces

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.

like image 820
zerkms Avatar asked Feb 21 '20 00:02

zerkms


People also ask

What is a type interface?

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

What is type interface in TypeScript?

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.

What is the difference between interface and type?

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.

What are interfaces in JavaScript?

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.


1 Answers

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.

like image 103
juanpa.arrivillaga Avatar answered Sep 23 '22 04:09

juanpa.arrivillaga