René's URL Explorer Experiment


Title: Reconsider making Mapping covariant in the key type · Issue #445 · python/typing · GitHub

Open Graph Title: Reconsider making Mapping covariant in the key type · Issue #445 · python/typing

X Title: Reconsider making Mapping covariant in the key type · Issue #445 · python/typing

Description: Confusion with invariant container types is one of the more common questions mypy users have. Often these can be easily worked around by using a covariant type such as Sequence instead of List. However, there is no fully covariant dictio...

Open Graph Description: Confusion with invariant container types is one of the more common questions mypy users have. Often these can be easily worked around by using a covariant type such as Sequence instead of List. How...

X Description: Confusion with invariant container types is one of the more common questions mypy users have. Often these can be easily worked around by using a covariant type such as Sequence instead of List. How...

Opengraph URL: https://github.com/python/typing/issues/445

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Reconsider making Mapping covariant in the key type","articleBody":"Confusion with invariant container types is one of the more common questions mypy users have. Often these can be easily worked around by using a covariant type such as `Sequence` instead of `List`. However, there is no fully covariant dictionary-like type -- `Mapping` is invariant in the key type, since the key type is used as an argument type of `__getitem__` and `get`. This is particularly problematic in Python 2, as mappings with `unicode` keys are common, and a mapping with `str` keys is not compatible with them, even though they are fine at runtime (at least if the keys are ascii only).\r\n\r\nI can see a few things we could do.\r\n\r\n**1) Don't care about unsafety**\r\n\r\nWe'd make `Mapping` covariant even though it's known to be unsafe (https://github.com/python/typing/pull/273). The argument is that the potential unsafety is less of a problem than the confusing user experience. This wouldn't help with certain related things like using a `unicode` key to access `Mapping[str, X]`, which is arguably okay.\r\n\r\nNote that this was [proposed and rejected](https://github.com/python/typing/pull/273) earlier.\r\n\r\n**2) Use `object` in `Mapping` argument types**\r\n\r\nWe'd make `Mapping` covariant and use `object` in the argument type of `__getitem__` and `get`. This would result in less effective type checking, but I'd consider this to still be correct at least for `get`, since it can always fall back to the default. Also, `__getitem__` would typically only generate a `KeyError` if given a key of an unrelated type, and this is arguably not a type error. Indexing operations on mappings can already fail with `KeyError`, and this isn't considered a type safety issue.\r\n\r\nWe could also recommend that type checkers special case type checking of `Mapping.__getitem__` and `Mapping.get` (and also the corresponding methods in subclasses such as `Dict`). A reasonable rule would be to require that the actual key type in code like `d[k]` overlaps with the declared key type. This would allow things like using `unicode` keys for `Mapping[str, int]`, which should perhaps be fine in Python 2. We could still reject things like `d[1]` if the declared key type is `str`, since `int` and `str` are not overlapping.\r\n\r\nSubclasses of `Mapping` that only support specific runtime key types would now be rejected. For example, this wouldn't work any more:\r\n\r\n```py\r\nclass IntMap(Mapping[int, int]):\r\n    def __getitem__(self, k: int) -\u003e int: ...   # needs an object argument\r\n    ...\r\n```\r\n\r\nHowever, it would be easy enough to refactor this to type check:\r\n\r\n```py\r\nclass IntMap(Mapping[int, int]):\r\n    def __getitem__(self, k: object) -\u003e int: ...\r\n        assert isinstance(k, int)  # sorry, can't deal with non-int keys\r\n        ...\r\n    ...\r\n```\r\n\r\nI think that this is reasonable -- the required assert (or cast) makes it clear that this is potentially unsafe.\r\n\r\n**3) Just teach users to work around using unions or type variables**\r\n\r\nMaybe keeping `Mapping` is invariant in the key type is reasonable. Often the lack of covariance can be worked around by using other type system features. Here are some examples:\r\n\r\n* Use `Union[Mapping[str, int], Mapping[unicode, int]]` instead of `Mapping[unicode, int]`.\r\n* Use `Mapping[AnyStr, int]` in Python 2 and `Mapping[str, int]` in Python 3 using a conditional type alias.\r\n* Define a type variable like `AnyText = TypeVar('AnyText', str, Text)` and use `Mapping[AnyText, int]`. This is a little awkward, since in Python 3 the values of the type variable would be `str` and `str`.\r\n\r\nI don't like these for a few reasons:\r\n* These are not intuitive.\r\n* These are inconsistent with other containers such as `Sequence`. \r\n* These are more verbose than just `Mapping[unicode, int]`.\r\n","author":{"url":"https://github.com/JukkaL","@type":"Person","name":"JukkaL"},"datePublished":"2017-06-28T15:35:21.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":13},"url":"https://github.com/445/typing/issues/445"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:3279550f-f02e-d6c6-315d-a6aecc80a060
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id82A8:11D194:64CCFD:86BBA2:6A629FF0
html-safe-nonce5025eaad707e2411360fd326520f99e40e3fd981ae22d1eb3d1138d46474c831
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MkE4OjExRDE5NDo2NENDRkQ6ODZCQkEyOjZBNjI5RkYwIiwidmlzaXRvcl9pZCI6IjU3ODI5NjYyNTk0NDY2MjAxNDQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac206a681fb8d591e57caf747dd1cc5a2e28270393ba04d7152762fb0500479887
hovercard-subject-tagissue:239205931
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/typing/445/issue_layout
twitter:imagehttps://opengraph.githubassets.com/c0636890f32ea46b32c3da71c0a951a13639208ccae8e174aeffc336e6f82ae4/python/typing/issues/445
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/c0636890f32ea46b32c3da71c0a951a13639208ccae8e174aeffc336e6f82ae4/python/typing/issues/445
og:image:altConfusion with invariant container types is one of the more common questions mypy users have. Often these can be easily worked around by using a covariant type such as Sequence instead of List. How...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameJukkaL
hostnamegithub.com
expected-hostnamegithub.com
Nonea6443033349a18134b517627f043d4a59a5110337b879810c7229c2c7e28eda0
turbo-cache-controlno-preview
go-importgithub.com/python/typing git https://github.com/python/typing.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id24604008
octolytics-dimension-repository_nwopython/typing
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id24604008
octolytics-dimension-repository_network_root_nwopython/typing
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
released6c6cacbe32d3ddfd1796fbd1a39b8fb47b87daf
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/typing/issues/445#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Ftyping%2Fissues%2F445
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
Code QualityEnforce quality at mergehttps://github.com/features/code-quality
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Ftyping%2Fissues%2F445
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Ftyping
Reloadhttps://github.com/python/typing/issues/445
Reloadhttps://github.com/python/typing/issues/445
Reloadhttps://github.com/python/typing/issues/445
Please reload this pagehttps://github.com/python/typing/issues/445
python https://github.com/python
typinghttps://github.com/python/typing
Notifications https://github.com/login?return_to=%2Fpython%2Ftyping
Fork 304 https://github.com/login?return_to=%2Fpython%2Ftyping
Star 1.8k https://github.com/login?return_to=%2Fpython%2Ftyping
Code https://github.com/python/typing
Issues 204 https://github.com/python/typing/issues
Pull requests 28 https://github.com/python/typing/pulls
Discussions https://github.com/python/typing/discussions
Actions https://github.com/python/typing/actions
Security and quality 0 https://github.com/python/typing/security
Insights https://github.com/python/typing/pulse
Code https://github.com/python/typing
Issues https://github.com/python/typing/issues
Pull requests https://github.com/python/typing/pulls
Discussions https://github.com/python/typing/discussions
Actions https://github.com/python/typing/actions
Security and quality https://github.com/python/typing/security
Insights https://github.com/python/typing/pulse
Reconsider making Mapping covariant in the key typehttps://github.com/python/typing/issues/445#top
resolution: wontfixA valid issue that most likely won't be resolved for reasons described in the issuehttps://github.com/python/typing/issues?q=state%3Aopen%20label%3A%22resolution%3A%20wontfix%22
https://github.com/JukkaL
JukkaLhttps://github.com/JukkaL
on Jun 28, 2017https://github.com/python/typing/issues/445#issue-239205931
#273https://github.com/python/typing/pull/273
proposed and rejectedhttps://github.com/python/typing/pull/273
resolution: wontfixA valid issue that most likely won't be resolved for reasons described in the issuehttps://github.com/python/typing/issues?q=state%3Aopen%20label%3A%22resolution%3A%20wontfix%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.