Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created November 22, 2022 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mypy-play/ba0ae4e284ea9a09007a3b84e183ad26 to your computer and use it in GitHub Desktop.
Save mypy-play/ba0ae4e284ea9a09007a3b84e183ad26 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from __future__ import annotations
from abc import abstractmethod
from typing import Protocol, TypeVar
T = TypeVar("T")
T_add = TypeVar("T_add", bound="Addable")
class Addable(Protocol):
def __add__(self: T, other: T) -> T:
pass
def foo(x: T_add, y: T_add) -> T_add:
return x + y
myint: int = foo(1, 2)
mylist: list[int] = foo([1], [2])
mydict: dict = foo({"a": 1}, {"b": 2})
@spookylukey
Copy link

This seems to work - myint and mylist are accepted, mydict is rejected for the right reason.

(You can put type hint dict[str, int] on mydict to silence a different error)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment