You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Invalid index type "Union[str, int]" for "Union[Mapping[str, Union[str, int]],
Mapping[int, Union[str, int]]]"; expected type "str" mypy(error)
Invalid index type "Union[str, int]" for "Union[Mapping[str, Union[str, int]],
Mapping[int, Union[str, int]]]"; expected type "int" mypy(error)
@JelleZijlstra, @hauntsaninja thank you for your replies! 🌞 I thought there was a good reason for this behavior.
I am closing this issue, since I see it was already discussed.
FWIW, I think I understood that Union is not the right tool to do the think I had in mind, described in my example above. The right tool is to define generic types for keys and values!
And I understood this, because in C# it would be the same (Union doesn't exist in C#, you have to use interfaces to describe something like union). I often take C# as example because I know it, it's static, and clearly it is mature about generics.
A basic example would be:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;namespacenetconsole{classProgram{// a function that accepts any kind of dictionary as input and returns // a new dictionary of only stringsstaticDictionary<string,string>Example<A,B>(Dictionary<A,B>dict)=>dict.ToDictionary(key =>key.ToString(), value =>value.ToString());staticvoidMain(string[]args){varx=newDictionary<string,int>(){{"a",1},{"b",2},{"c",3}};vara=Example(x);}}}
Activity
RobertoPrevato commentedon Mar 2, 2020
Additionally:
JelleZijlstra commentedon Mar 3, 2020
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.
hauntsaninja commentedon Mar 3, 2020
It's because
__getitem__andgetcould do unsound things.python/typing#445
#1114
RobertoPrevato commentedon Mar 3, 2020
@JelleZijlstra, @hauntsaninja thank you for your replies! 🌞 I thought there was a good reason for this behavior.
I am closing this issue, since I see it was already discussed.
FWIW, I think I understood that
Unionis not the right tool to do the think I had in mind, described in my example above. The right tool is to define generic types for keys and values!And I understood this, because in C# it would be the same (
Uniondoesn't exist in C#, you have to useinterfacesto describe something like union). I often take C# as example because I know it, it's static, and clearly it is mature about generics.A basic example would be:
RobertoPrevato commentedon Mar 3, 2020
PS. I see the same was discussed here #6001