Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining an interface in Python

Tags:

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.

like image 735
Bruno Brant Avatar asked Jun 19 '26 23:06

Bruno Brant


1 Answers

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.

like image 75
edd313 Avatar answered Jun 21 '26 14:06

edd313



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!