Skip to content

Disallow Mapping as argument type? #3576

Closed
@srittau

Description

@srittau

This came up in #3569. See also the later comments in python/typing#11 for background. Mapping is not a protocol (as opposed to most other typing ABCs). This mean code like the following will not work:

from typing import Iterator, Mapping

class MyMap:
    def __getitem__(self, key: str) -> int:
        return 0
    def __iter__(self) -> Iterator[str]:
        return iter([])
    def __len__(self) -> int:
        return 0
    def __contains__(self, key: object) -> bool:
        return False

def foo(x: Mapping[str, int]) -> None:
    pass

foo(MyMap())  # error: Argument 1 to "foo" has incompatible type "MyMap"; expected "Mapping[str, int]"

Deriving MyMap from Mapping[str, int] works, though. I suggest we don't allow new submissions to use Mapping as argument type and work towards removing existing uses. Instead they should use a custom protocol, which can also be narrower than Mapping.

Metadata

Metadata

Assignees

No one assigned

    Labels

    project: policyOrganization of the typeshed project

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions