dict[int, bool] | dict[str, bool] being interpreted as dict[int | str, bool]
#11199
Replies: 2 comments 1 reply
-
|
Hey! I ran into the same Pyright issue with from collections.abc import Mapping
from typing import TypeAlias, TypeVar
K = TypeVar("K", int, str)
MapType: TypeAlias = Mapping[int, "MapType | set[K] | bool"] | Mapping[str, "MapType | set[K] | bool"]
def ensure_dict_recursive(value: MapType | set[K] | bool) -> MapType:
if isinstance(value, Mapping):
return {k: ensure_dict_recursive(v) if isinstance(v, (Mapping, set)) else v for k, v in value.items()}
elif isinstance(value, set):
return {k: True for k in value}
return valueThis keeps Pyright happy with recursive dicts and mixed key types. I’m working on a PR to make this easier for everyone... |
Beta Was this translation helpful? Give feedback.
-
|
Yep, that’s the key limitation. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Dict comprehension from
dict[int, bool] | dict[str, bool]results indict[int | str, bool]which is incorrect. This is likely due to the fact that a the key itself would beint | strand that is used as the source of truth.I got it working by using generics, but when trying to use recursion it fell apart again. I think because it's not treating the recursive
Kas a new type and instead keeps the parent type?Type "Mapping[str, set_type | map_type | bool]" is not assignable to type "Mapping[int, map_type | set_type | bool] | set[int]"Beta Was this translation helpful? Give feedback.
All reactions