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
The problem IIRC is that users expect Mapping to be covariant in the key,
e.g. they have an object of type Mapping[str, int] and they want to be able
to pass that off to a function that expects a Mapping[object, int].
Oh, there's a gotcha - when extracting keys from it, they can be almost anything. So it should be type checked.
So either there should be Mapping type without keys() and items(), or people will need to ask for Callable[[K], V] everywhere (which mixing with .get() means Callable[[K], Optional[V]] too). :\
Still, I want to note that the only cost of making K contravariant is making keys() return AbstractSet[object] instead of AbstractSet[K] (or perhaps AbstractSet[K_contra] has the same effective meaning?). I think it might be worth it since keys() is not the main use of Mapping.
The best of both worlds is to let the user choose, like -K in scala, in the user side.
Activity
gvanrossum commentedon Sep 14, 2016
Have you tried it? (Not a rhetorical question.)
The problem IIRC is that users expect Mapping to be covariant in the key,
e.g. they have an object of type Mapping[str, int] and they want to be able
to pass that off to a function that expects a Mapping[object, int].
elazarg commentedon Sep 14, 2016
But that's not type-safe, so warning about it at least makes sense - it can catch errors, whereas the other way around does not.
I needed it (for the Expression/Node story) and it worked only after changing it to be contravariant.
gvanrossum commentedon Sep 14, 2016
elazarg commentedon Sep 14, 2016
Oh, there's a gotcha - when extracting keys from it, they can be almost anything. So it should be type checked.
So either there should be Mapping type without keys() and items(), or people will need to ask for Callable[[K], V] everywhere (which mixing with .get() means Callable[[K], Optional[V]] too). :\
gvanrossum commentedon Sep 14, 2016
elazarg commentedon Sep 14, 2016
Confusing names....
elazarg commentedon Sep 15, 2016
Still, I want to note that the only cost of making K contravariant is making keys() return
AbstractSet[object]instead ofAbstractSet[K](or perhapsAbstractSet[K_contra]has the same effective meaning?). I think it might be worth it since keys() is not the main use of Mapping.The best of both worlds is to let the user choose, like
-Kin scala, in the user side.Add intersphinx links for 3.13 typing features (python#550)