Daniel Malachov
Daniel Malachov

Reputation: 1842

Python type hints derived from other function annotations

I have a function and inside i call another function with same params as in my function. Types are defined by inner function, by i want to control it.

Is there any way how to use same type hints like inner function?

What i tried

from typing import get_type_hints, Any

def inner(inner_param: int) -> int:
    return inner_param

a = get_type_hints(obj=inner).get("inner_param", Any)

def outer(my_param: a) -> None:
    result = inner(my_param)
    print(result)

outer("asd")  # Alert should go here

Though a is class <class 'int'> (same as int) Static type analysis not working for me (VS Code - Pylance).

Is there a problem with code? Or this is not possible yet? Or it's a problem of static type analysis tool?

In python docs, it's stated, that a get_type_hints will not work with aliases, but that PEP 563 (from __future__ import annotations) and later evaluation could solve it.

If i convert int type to str (or use str value from annotation) it's still not working.

Use case is that if in the future inner function is changed, i don't want to have bad types here.

Upvotes: 2

Views: 875

Answers (1)

I would say that you're doing everything correctly. The source of the problem is the type analysis tool. Pylance, as you said, is a static type analysis tool. Which means it doesn't execute any line to analyse your code.

However, your variable a requires execution to be defined. Even if get_type_hints's result may be somehow guessed statically (Pylance won't do it for you, but theoretically it seems possible), result of applying .get("inner_param", Any) to it is unknown statically and can only be defined in runtime.

Hence, the short answer to your question is: "it's a problem of static type analysis tool". The long one is already described above.

Upvotes: 2

Related Questions