Skip to content

Commit dd7678b

Browse files
committed
Add python/copy_type.py
1 parent fe42b26 commit dd7678b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

python/copy_type.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from abc import ABC, abstractmethod
2+
from typing import Any, TypeVar, Callable
3+
from typing_extensions import override, reveal_type
4+
5+
6+
_T = TypeVar("_T")
7+
8+
9+
class Module:
10+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
11+
return self.forward(*args, **kwargs)
12+
13+
@abstractmethod
14+
def forward(self, *args: Any, **kwargs: Any) -> Any:
15+
raise NotImplementedError
16+
17+
18+
def copy_type(f: _T) -> Callable[[Any], _T]:
19+
# From https://github.com/python/typing/issues/769#issuecomment-903760354
20+
return lambda x: x
21+
22+
23+
class Implementation(Module):
24+
@override
25+
def forward(self, x: int, /, y: str) -> int:
26+
return x * int(y)
27+
28+
# This boilerplate would need to be pasted into any class derived from Module
29+
# to get the right typing for `__call__`
30+
@copy_type(forward)
31+
def __call__(self, *a: Any, **k: Any) -> Any:
32+
return super().__call__(*a, **k)
33+
34+
35+
imp = Implementation()
36+
print(imp(2, "3"))
37+
print(imp("2", "3"))
38+
39+
# mypy says:
40+
# copy_type.py:34: error: Argument 1 to "__call__" of "Implementation" has incompatible type "str"; expected "int" [arg-type]
41+
# Found 1 error in 1 file (checked 1 source file)

0 commit comments

Comments
 (0)