Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Union[]s as dict[] values #2300

Closed
Herst opened this issue Oct 21, 2016 · 1 comment
Closed

Union[]s as dict[] values #2300

Herst opened this issue Oct 21, 2016 · 1 comment
Labels

Comments

@Herst
Copy link
Contributor

Herst commented Oct 21, 2016

Mypy does not detect the subtype relation (correct term?) when it comes to dict values:

if False:
    from typing import Union

# works
foo1 = 0 # type: int
bar1 = foo1 # type: Union[int, str]

# "Incompatible types in assignment"
foo2 = {} # type: dict[str, int]
bar2 = foo2 # type: dict[str, Union[int, str]]

Mypy 0.4.5

@gvanrossum
Copy link
Member

This is actually correct, because Dict[str, int] is not a subtype of Dict[str, Union[str, int]] (even though int is a subtype of Union[int, str]). The reason is that Dict is defined as invariant in its type parameters, and that is done because Dict is mutable.

Consider this code:

a = {}  # type: Dict[str, int]
def f(b: Dict[str, Union[int, str]]) -> None:
    b['x'] = 'y'
f(a)

If we allowed that call to f(a), a would end up with a string value! To prevent this we don't consider Dict[str, Union[int, str]] a subtype of Dict[str, int].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants