4 ms·
In Python, can typings define a property added to a function? Example, I have some Redux helpers that are functions, but those functions also define a `.action
by c-hendricks 3y ago
In Python, can typings define a property added to a function?
Example, I have some Redux helpers that are functions, but those functions also define a `.actionType` property. TypeScript handles that.
edit: accidentally wrote "object" instead of "function"
- dataangel 3y agoI believe you could have a Protocol that requires the property and that the object is Callable.
- c-hendricks 3y agoAh, 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 }
- nerdponx 3y agoThe 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...