-
Notifications
You must be signed in to change notification settings - Fork 249
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
Make Mapping covariant in keys (too). #273
Conversation
@gvanrossum def fun(m: Mapping[float, Any]):
return m[0.1]
class StrangeMap(Mapping[int, Any]):
def __getitem__(self, item):
return item << 5
fun(StrangeMap()) If Of course this example is a bit artificial, but I think there are realistic examples just going the same way. |
@JukkaL What do you think? On Wed, Aug 31, 2016 at 11:56 AM, Ivan Levkivskyi notifications@github.com
--Guido van Rossum (python.org/~guido) |
As discussed in python/typeshed#510, this is clearly unsafe, but maybe the cases where the unsafety might manifest itself are more common that I originally thought :-( Making it covariant in the value type should be less of a problem. We could use a separate type variable |
OK, I'll close this for now, leaving Mapping covariant in the value but not in the type. (Alas, mypy doesn't understand that union yet, so get() still requires |
>>> issubclass(int, float)
False
>>> isinstance(1, float)
False |
But it is in for static type checkers, and this is specified by PEP 484. |
Is the only issue making Mapping covariant in the key with int/float? For example, I expect Tangential question - is the covariance/contravariance specified by a PEP? I couldn't find anything other than PEP 484 which says:
which seems to indicate Mapping should be covariant in the key (but is slightly ambiguous, I suppose). If I've captured the objections to making Mapping covariant in the key, then my take is that not making Mapping covariant in the key is foregoing a generally useful feature in good code for oddities some might experience in not-so-good code. But I suspect I may be missing some cases. |
Whole-type variance is not fine-grained enough to describe the relation here. Indexing is actually contravariant, setting is covariant as are other operations. The variance of the type, as it appears on a function, depends entirely on how the object is used. This is also related to python/typeshed#7121 and python/typeshed#7015 where methods are contravariant, but the type is covariant. There is no way to describe this with Python's type system, as it stands. |
…n the key type See: - python/typing#445 - python/typing#273
See python/typeshed#510