[Python] How to write type hints for recursive function computing depth in Python?

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote the following function in Python 3.12:

    # pyright: strict

    from collections.abc import Iterable, Mapping
    from typing import Any

    type Nested = Any | Mapping[str, Nested] | Iterable[Nested]


    def _get_max_depth(obj: Nested) -> int:
    if isinstance(obj, Mapping):
    return max([0] + [_get_max_depth(val) for val in obj.values()]) + 1
    elif isinstance(obj, Iterable) and not isinstance(obj, str):
    return max([0] + [_get_max_depth(elt) for elt in obj]) + 1
    else:
    return 0


    However, pyright 1.1.398 complains that:

    demo-pyright.py
    demo-pyright.py:11:42 - error: Argument type is partially unknown
    Argument corresponds to parameter "obj" in function "_get_max_depth"
    Argument type is "Any | Mapping[str, Any | ... | Iterable[Nested]] | Iterable[Any | Mapping[str, Nested] | ...] | Unknown" (reportUnknownArgumentType)
    demo-pyright.py:11:51 - error: Type of "val" is partially unknown
    Type of "val" is "Any | Mapping[str, Nested] | Iterable[Nested] | Unknown" (reportUnknownVariableType)
    demo-pyright.py:13:42 - error: Argument type is partially unknown
    Argument corresponds to parameter "obj" in function "_get_max_depth"
    Argument type is "Unknown | Any | Mapping[str, Any | ... | Iterable[Nested]] | Iterable[Any | Mapping[str, Nested] | ...]" (reportUnknownArgumentType)
    demo-pyright.py:13:51 - error: Type of "elt" is partially unknown
    Type of "elt" is "Unknown | Any | Mapping[str, Nested] | Iterable[Nested]" (reportUnknownVariableType)
    4 errors, 0 warnings, 0 informations


    To silence pyright, I could use the following workarounds:

    • Change Any to concrete types, such as int | str.
    • Replace Mapping with dict.
    • Replace Iterable with list.

    However, I am not satisfied with these workarounds since the function should be generic.

    Is there a way to write type hints that satisfy pyright in strict mode in this case?

    Continue reading...

Compartilhe esta Página