-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Mapping with Union for keys #8477
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
Comments
Additionally: a: Union[Mapping[str, Union[str, int]],
Mapping[int, Union[str, int]]]
b: Union[str, int] = 20
c = a[b] < mypy reports two errors, written below
|
This is generally because of https://mypy.readthedocs.io/en/stable/common_issues.html#invariance-vs-covariance. The key argument to Mapping is invariant. I don't remember exactly why this is, but I think we tried making it covariant at some point and it caused problems, so we had to revert. |
It's because |
@JelleZijlstra, @hauntsaninja thank you for your replies! 🌞 I thought there was a good reason for this behavior. FWIW, I think I understood that from typing import *
A = TypeVar("A", str, int)
B = TypeVar("B", str, int)
def example2(value: Mapping[A, B]):
...
x: Mapping[str, int] = {
"a": 1,
"b": 2,
"c": 3
}
example2(x)
y: Mapping[str, str] = {
"a": "1",
"b": "2",
"c": "3"
}
example2(y) And I understood this, because in C# it would be the same ( A basic example would be: using System;
using System.Collections.Generic;
using System.Linq;
namespace netconsole
{
class Program
{
// a function that accepts any kind of dictionary as input and returns
// a new dictionary of only strings
static Dictionary<string, string> Example<A, B>(Dictionary<A, B> dict)
=> dict.ToDictionary(key => key.ToString(), value => value.ToString());
static void Main(string[] args)
{
var x = new Dictionary<string, int>() {
{"a", 1},
{"b", 2},
{"c", 3}
};
var a = Example(x);
}
}
} |
PS. I see the same was discussed here #6001 |
Hi,
Considering the following example:
Results in error:
Argument 1 to "example" has incompatible type "Mapping[str, int]"; expected "Mapping[Union[str, int], Union[str, int]]"mypy(error)
.Shouldn't MyPy accept the
Mapping[str, int]
to be a valid instance ofMapping[Union[str, int], Union[str, int]]
?This behavior looks surprising, because
Union
is supported for values, but not for keys. If the function annotation is modified this way:Then mypy is happy. Version: mypy==0.761
The text was updated successfully, but these errors were encountered: