Bruno Brant
Bruno Brant

Reputation: 8564

Defining an interface in Python

I'm wondering whether we can use the typing package to produce the definition of an "interface", that is, a class/object in Python 3.

It seems that the usual way to define an "interface" in Python is to use an abstract classdefined using ABC, and use that as your type parameter. However, since Python is dynamically typed, a fully abstract type is an interface that is nothing more than a typing hint for python. In runtime, I would expect to have zero impact from said interface. A base class can have methods that are inherited, and that's not what I want.

I'm based a lot of this on my experience with TypeScript - it enables us to very easily define object types through interface or the type keyword, but those are only used by the type checker.

Let me make my use case clearer with an example:

Let's say I'm defining a function foo as below:

def foo(bar):
    nums = [i for i in range(10)]
    result = bar.oogle(nums)
    return result

foo is, therefore, a method that expects to receive an instance of an object that must have a method oogle that accepts a list of integers. I want to make it clear to callers that this is what foo expects from bar, but bar can be of any type.

Upvotes: 6

Views: 6117

Answers (1)

edd313
edd313

Reputation: 1459

PEP544 introduced Protocol classes, which can be used to define interfaces.

from typing import Any, List, Protocol

class Bar(Protocol):
    def oogle(self, quz: List[int]) -> Any:
       ...

def foo(bar: Bar):
    nums = [i for i in range(10)]
    result = bar.oogle(nums)
    return result
 

If you execute your script using Python you will not see any difference though. You need to run your scripts with Mypy, which is a static type checker that supports protocol classes.

Upvotes: 9

Related Questions