Inference on Literal Types

I find the current pyright’s behavior useful.
It lets me define a constant which appears immutable to the import sites, while remaining mutable in the defining file, allowing for late initialization.

# names.py
__all__ = ("NAME_TO_ID", "populate")

NAME_TO_ID: abc.Mapping[str, int] = {}
reveal_type(NAME_TO_ID)  # dict[str, int]


def populate(data: abc.Mapping[str, int], /) -> None:
    NAME_TO_ID.update(data)
# mod1.py
from names import NAME_TO_ID

reveal_type(NAME_TO_ID)  # abc.Mapping[str, int]

Note that this could already be achieved by introducing a private variable/constant typed as the mutable variant, but if pyright lets me save typing I’ll take it ¯\_(ツ)_/¯

1 Like