-
Consider the following: T = TypeVar("T")
def register(
callback: Callable[[Connection, Channel, T], Coroutine[None, None, None] | None],
) -> None:
# Parse the paylod_type.
# I'm not sure if iterating over the dictionary returned by `get_type_hints` is guaranteed to return
# the argument name and annotation in the order they are defined in the callback, but it is working for
# now. This should be confirmed.
values = list(get_type_hints(callback).values())
payload_type: type[T] = values[2] If I want to access the type hint of the third argument within the given callback, is this the correct way to do it? Another way I had considered was using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It's also worth noting that So you would need to use |
Beta Was this translation helpful? Give feedback.
It's also worth noting that
Callable
is too broad of aProtocol
fortyping.get_type_hints
, since it also accepts lambdas (which don't have annotations) and any object that implements__call__
includingtype
, which is also a valid argument forget_type_hints
, but at that point you would be inspecting the attributes of the class and not the parameters of the__init__
/__new__
method.So you would need to use
inspect.signature
anyways to properly handle all the different kinds of callables with reasonable certainty, that you didn't miss some kind of corner case. There's some internal functions in the typing module that can give you an idea how to deal with things likeAnnotated
and forward re…