pythonreflectionpython-typingcallable

How to inspect return type of Callable


Let's say I have something like the following:

import inspect
from collections.abc import Callable  # Using Python 3.10+
from typing import get_type_hints

def foo(arg: Callable[..., int]) -> None:
    pass

type_hints = get_type_hints(foo)["arg"]
annotation = inspect.signature(foo).parameters["arg"].annotation
# How can one get the return type `int` from either of these?

I can figure out how to get to the Callable type hint. From there, how can one inspect the return type of the Callable?


Solution

  • To avoid access to dunder attributes, which in general is unsafe and can break between version releases, you should use a method provided by typing module:

    type_hint = get_type_hints(foo)["arg"]
    arg_types, return_type = get_args(type_hint)
    

    This works for any Callable. arg_types is Ellipsis (...) or a list of args (also may be a typing.ParamSpec or typing.Concatenate, if you use them), return_type is whatever occupies 2nd place.