79816316

Date: 2025-11-11 07:01:03
Score: 3
Natty:
Report link
  1. 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.

    1. Why? TypeVar substitution only works when the type is known at type-check time, usually from the argument type, not its value.

    2. 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

Reasons:
  • Blacklisted phrase (0.5): How can i
  • Blacklisted phrase (0.5): Why?
  • RegEx Blacklisted phrase (2): downvote
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: ChichiKugel