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

Add example of non-mutable mapping to cheat sheet #7620

merged 4 commits into from Oct 9, 2019


Copy link

MarcoGorelli commented Oct 4, 2019

closes #7617


This comment has been minimized.

Copy link

msullivan commented Oct 4, 2019

Thinking about this a bit, this example is correct but I think fails to capture the main reason you usually want to use Mapping over MutableMapping: to ensure that even if the mapping happens to be mutable (which it usually is, since it is usually just a dict), that the function doesn't mutate it.

This is useful in two ways:

  1. Just in a general correctness/reasoning sense. Making it immutable means the caller can't mutate it, which makes reasoning easier and might prevent someone introducing a later change that mutates it.
  2. From a type system perspective, Mapping is covariant in its second argument, which means that you can, for example, pass a Dict[int, str] to a function expecting a Mapping[int, Optional[str]], for example. (Which you can't do if the function took a Dict or a MutableMapping)
Marco Gorelli added 3 commits Oct 7, 2019

This comment has been minimized.

Copy link
Contributor Author

MarcoGorelli commented Oct 7, 2019

Ah, I understand - so the difference isn't in the object you pass, but in what you do with that object. I've tried updating the PR so this is more explicit, but perhaps it's clear enough as is, in which case, feel free to close this :)

Copy link

gvanrossum left a comment


@gvanrossum gvanrossum merged commit 6f8480c into python:master Oct 9, 2019
1 check passed
1 check passed
continuous-integration/travis-ci/pr The Travis CI build passed
@MarcoGorelli MarcoGorelli deleted the MarcoGorelli:non-mutable-mapping branch Oct 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
3 participants
You can’t perform that action at this time.