2 ms·
The typical approach to this in Python is to define a callable class instead. If you define the __call__() method on a class, instances of the class will be cal
by nerdponx 3y ago
The typical approach to this in Python is to define a callable class instead. If you define the __call__() method on a class, instances of the class will be callable.
class IntAdder:
def __init__(self, x: int) -> None:
self.x = x
def __call__(self, y: int) -> int:
return self.x + y
def __str__(self) -> str:
return f"({self.x} + ??)"
add1 = IntAdder(1)
assert add1(3) == 4
print(add1)
# (1 + ??)
As mentioned in the sibling comment, you can define a Protocol which is analogous to an interface, so if you had a protocol like this:
from typing import Protocol, TypeVar
T = TypeVar("T")
class ValueUpdater(Protocol[T]):
def __call__(self, y: T) -> T: ...
Then IntAdder would be considered a subclass of ValueUpdater[int] by the type checker. Demo: https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=strict&gist=345aeaaa8bfb0eef387b930bdf6ee295 https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=strict&g...