Re:TypeScript Is Surprisingly OK for Compilers
by dataangel on Friday August 18, 2023 @12:16PM
(#37177828)
I believe you could have a Protocol that requires the property and that the object is Callable.
Re:TypeScript Is Surprisingly OK for Compilers
by c-hendricks on Friday August 18, 2023 @12:22PM
(#37177929)
Ah, that's not really that different than in TypeScript then. There you have to define a callable interface, and can add whatever properties you want
interface SomethingCallableWithAnExtraProperty {
// This means you can call it like a function.
(args: Whatever): SomethingReturned
// And since it's an interface, you can still do interface-y things
anotherProperty: string
}
Re:TypeScript Is Surprisingly OK for Compilers
by nerdponx on Friday August 18, 2023 @03:06PM
(#37180563)
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&g...
Example, I have some Redux helpers that are functions, but those functions also define a `.actionType` property. TypeScript handles that.