You cannot make the type checker infer the return type from a runtime argument like rtype: type[T]. The type checker sees that both str and int are possible return types and cant guarantee which will be returned at call sites.
Why? TypeVar substitution only works when the type is known at type-check time, usually from the argument type, not its value.
How can it be done? Overloads
from typing import overload
VALUES: dict[str, str] = {"SIZE": "100", "ADDR": "0x100", "NAME": "potato"}
@overload
def get_parameter(parameter: str, rtype: type[int]) -> int: ...
@overload
def get_parameter(parameter: str, rtype: type[str]) -> str: ...
def get_parameter(parameter: str, rtype: type[str] | type[int] = str) -> str | int:
value = VALUES[parameter]
if rtype is int:
return int(value, 0)
return value
2. Yes, the overload works in Python 3.10 as long as youre using from typing import overload
3. Yes, the example above shows defaulting rtype to str, but you can default to int if you prefer:
def get_parameter(parameter: str, rtype: type[str] | type[int] = int) -> str | int:
# implementation...
However, the type checker will assume calls without rtype return int. You should add corresponding overload for that:
@overload
def get_parameter(parameter: str) -> int: ...
IDK if this helps you but I hope so - If it does not help you just downvote my answer or I can delete it if you want me to.
Have a great day.
PS: i dont know either why the downvotes xD