Skip to content

Type constraints: dict.get doesn't accept Union type as key #1472

Closed
@ddfisher

Description

@ddfisher

Passing an overly-general Union to dict.get, like this:

from typing import Union

x = 5  # type: Union[int, str]
{ 1: 1 }.get(x, 0)

results in this error:

test.py:4: error: Argument 1 to "get" of "dict" has incompatible type "Union[int, str]"; expected "int"

Arguably, this should be allowed, because get provides a default if the item is not found (unlike __getitem__). But by that logic, potentially any type should be a valid argument to get, which doesn't seem right.
@gvanrossum: further thoughts?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions