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

closes #7617

@msullivan
Copy link
Collaborator

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)

@MarcoGorelli
Copy link
Contributor Author

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 gvanrossum left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

@gvanrossum gvanrossum merged commit 6f8480c into python:master Oct 9, 2019
@MarcoGorelli MarcoGorelli deleted the non-mutable-mapping branch October 10, 2019 10:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mapping and MutableMapping use the same example argument in docs
3 participants