Type inference across functions / reuse type hints

75 Views Asked by At

I have one function within an external library that has a complicated type hint ("inner"). In my code, I have another function ("outer") calling this function. One of the paramters of this function will be passed on to the hinted function. I would like to have mypy typecheck the parameter. How can I achieve this without copying the complicated type hint?

A minimal example would be

def inner(x: int) -> None:
    ...

def outer(x, y: str) -> None:
    """function that needs a typehint for x"""
    inner(x)

# This should throw an error
outer(x="a", y="a")

So I am looking for a way to define a TypeAlias based in the types of a parameter of an external inner function (which I cannot edit) without copying the type hints (and updating them if the inner functions type hints change)

1

There are 1 best solutions below

1
Mark On

You can use TypeAlias to assign the type to a variable, then reuse it in both functions:

from typing import TypeAlias

X: TypeAlias = int
def inner(x: X) -> None:
    ...

def outer(x: X, y: str) -> None:
    """function that needs a typehint for x"""
    inner(x)

# This should throw an error
outer(x="a", y="a")

Edit: Apologies, I've just noticed the comment about it being an external library - you could monkey patch it to expose the Alias as a separate variable.