Reputation: 315
I have a method that takes a callback function as an argument.
I want to specify a type hint for the callback function signature.
The problem is the signature of the callback function is:
def callback_function(event, token, *args)
where
type(event) = EventClass
type(token) = str
type(args) = tuple # of str
I could write this as:
callable[[...], returntype]
but I would like to tighten the type checking to be something useful, at least to making sure event
and token
are specified correctly.
Suggestions, please?
Upvotes: 0
Views: 390
Reputation: 166
Consider using Protocol for this matter, as answered before.
For your specific case it will look like this:
from typing import Protocol, TypeAlias
returntype: TypeAlias = int
class MyCallable(Protocol):
def __call__(self, event: EventClass, token: str, *args: str) -> returntype: ...
def some_function(callback: MyCallable): ...
Upvotes: 1