Skip to content Skip to sidebar Skip to footer

Exclude Type In Python Typing Annotation

I wrote the following function: def _clean_dict(d): return {k: v for k, v in d.items() if v is not None} I want to add type annotations to the function: def _clean_dict(d: Dic

Solution 1:

Python type hinting can't exclude types. You can't exclude Nones, strs or any another type.

The only thing you can use to try to emulate None exclusion is to use Union and write every type you are actually using in the dictionary.

Solution 2:

Given that you are willing to fix the types of keys and values when the function is called you can use generics to make this explicit. This still potentially allows instances of V to be None, but it makes the intent pretty clear. Note that you have to use Mapping because of variance issues. However, this is preferable anyway.

from typing import *


K = TypeVar("K")
V = TypeVar("V")


def_clean_dict(d: Mapping[K, Optional[V]]) -> MutableMapping[K, V]:
    return {k: v for k, v in d.items() if v isnotNone}

With this definition mypy correctly turns optional into non-optional types.

# clean_dict.py

d = {"a": 1, "b": 2, "c": None}
reveal_type(d)
reveal_type(_clean_dict(d))

$ mypy clean_dict.py

note: Revealed typeis'builtins.dict[builtins.str*, Union[builtins.int, None]]'
note: Revealed typeis'typing.MutableMapping[builtins.str*, builtins.int*]'

Post a Comment for "Exclude Type In Python Typing Annotation"