Skip to content

collections.ChainMap has wrong type hint for self.maps, rendering it "immutable" #6042

@ramalho

Description

@ramalho

Typeshed annotates collections.ChainMap as:

class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]):
    maps: list[Mapping[_KT, _VT]]
    def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ...
    def new_child(self: Self, m: Mapping[_KT, _VT] | None = ...) -> Self: ...

The self.maps attribute holds the chained mappings. It should be annotated as list[MutableMapping[_KT, _VT]].

The *maps parameter of __init__ and the m parameter of new_child need to be MutableMapping[_KT, _VT] as well.

As it is, the implementation in the standard library violates the type hint for self.maps in its __setitem__ method:

    def __setitem__(self, key, value):
        self.maps[0][key] = value

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions