Skip to content

Instantly share code, notes, and snippets.

@thesadru
Created June 14, 2021 12:36
Show Gist options
  • Save thesadru/1ca1ffc0f577402670cfcf4c7382bb22 to your computer and use it in GitHub Desktop.
Save thesadru/1ca1ffc0f577402670cfcf4c7382bb22 to your computer and use it in GitHub Desktop.
Proper annotation of python's add operator
"""An example of how deep python annotations can go.
Here I show a possible way to annotate an add() function to account for as many cases as possible.
We assume that the add() function simply adds the two numbers and does not call internal __add__ or __radd__ methods.
"""
from typing import Protocol, overload
T_contra = TypeVar('T_contra', contravariant=True)
T_co = TypeVar('T_co', covariant=True)
class SupportsAdd(Protocol[T_contra, T_co]):
def __add__(self, x: T_contra) -> T_co: ...
class SupportsRAdd(Protocol[T_contra, T_co]):
def __radd__(self, x: T_contra) -> T_co: ...
@overload
def add(x: SupportsAdd[T_contra, T_co], y: T_contra) -> T_co: ...
@overload
def add(x: T_contra, y: SupportsRAdd[T_contra, T_co]) -> T_co: ...
def add(x, y):
return x + y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment