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
merged 4 commits into from Oct 9, 2019

Conversation

@MarcoGorelli
Copy link
Contributor

MarcoGorelli commented Oct 4, 2019

closes #7617

@msullivan

This comment has been minimized.

Copy link
Collaborator

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
@MarcoGorelli

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
Member

gvanrossum left a comment

Nice!

@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
Details
@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
Projects
None yet
3 participants
You can’t perform that action at this time.