[Python] How to type hint np.nan?

Discussão em 'Python' iniciado por Stack, Fevereiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function that calculates a machine's "status" value - either on (1) or off (0). But also I want it to return a np.nan if the input value is None or nan (like what pandas would do. My goal is to apply this on a pd.DataFrame).

    def calc_status(raw_value: int) -> int:
    if raw_value is None or np.isnan(raw_value):
    return np.nan
    # do other checks & calcs
    return status


    Since the function will only return 1/0 integers, the return type hint can be Literal[0, 1]. But the function can also return nan... type(np.nan) is float. I don't want to hint Union[Literal[0, 1], float], because that "float" feels too generic. The function can't just return any floats, such as 1.5 or 1.0. It can only return nan, which turns out to be a "float".

    At first I tried Literal[0, 1, np.nan], but that seems to be invalid, with PyCharm's static type checker showing this warning:


    'Literal' may be parameterized with literal ints, byte and unicode strings, bools, Enum values, None, other literal types, or type aliases to other literal types
    ​

    Continue reading...

Compartilhe esta Página