René's URL Explorer Experiment


Title: Mypy doesn't narrow a matched object's type (generic or not) based on attribute subpattern match · Issue #19081 · python/mypy · GitHub

Open Graph Title: Mypy doesn't narrow a matched object's type (generic or not) based on attribute subpattern match · Issue #19081 · python/mypy

X Title: Mypy doesn't narrow a matched object's type (generic or not) based on attribute subpattern match · Issue #19081 · python/mypy

Description: Bug Report Summary TLDR Mypy doesn't narrow a parent object's type when subpattern-matching on one of its attributes. Longer summary Mypy doesn't always use attribute sub-pattern matches (e.g. case Err(ValueError())) to narrow the parent...

Open Graph Description: Bug Report Summary TLDR Mypy doesn't narrow a parent object's type when subpattern-matching on one of its attributes. Longer summary Mypy doesn't always use attribute sub-pattern matches (e.g. case...

X Description: Bug Report Summary TLDR Mypy doesn't narrow a parent object's type when subpattern-matching on one of its attributes. Longer summary Mypy doesn't always use attribute sub-pattern matche...

Opengraph URL: https://github.com/python/mypy/issues/19081

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Mypy doesn't narrow a matched object's type (generic or not) based on attribute subpattern match","articleBody":"# Bug Report\n\n## Summary\n\n### TLDR\n\nMypy doesn't narrow a parent object's type when subpattern-matching on one of its attributes.\n\n### Longer summary\n\nMypy doesn't always use [attribute sub-pattern matches](https://peps.python.org/pep-0636/#matching-positional-attributes) (e.g. `case Err(ValueError())`) to narrow the parent object (e.g. `Err[ValueError | AttributeError]` isn't narrowed to `Err[ValueError]`). This prevents an error-free type-level exhaustiveness check using `assert_never` after matching all possible patterns.\n\nSome of the examples below show that mypy successfully narrows the attribute itself, but doesn't propagate this narrowing up to the object being matched, even when there's a generic type argument that could be narrowed. E.g. if `val` is narrowed to `ValueError`, mypy should be able to narrow the object from `Err[ValueError | AttributeError]` to `Err[ValueError]`.\n\nIdeally, in the `case _` after exhausting all patterns/subpatterns, the object could be narrowed to `Never`.\n\nIt's possible that it's expected that mypy can't narrow a non-generic type, if it needs a type argument that can explicitly be narrowed. I've included a non-generic example below anyway though, for completeness, since it does have all its patterns matched but fails the exhaustiveness check.\n\n### Context\n\nThe real-world context for this issue was an attempt to pattern match on [poltergeist's `Result = Ok[_T] | Err[_E]` type](https://github.com/alexandermalyga/poltergeist/blob/main/poltergeist/result.py), where Err can be constrained to a specific subset of exceptions. Finishing a `match result:` statement with `case _: assert_never(result)` only works if we avoid matching error sub-patterns: i.e. if we do `case Err(err)` and avoid `case Err(ValueError())`.\n\nIn this context, this issue takes away from some of the potential power of a library like poltergeist, which seeks to make error handling more explicit and type-safe.\n\nI guess a workaround could be to just add a nested `match` statement on `err._value` itself within the `case Err(err)` block. But that feels unfortunate to have to do when `match` was built to be powerful around subpattern matching, and [PEP 636 – Structural Pattern Matching: Tutorial](https://peps.python.org/pep-0636/#composing-patterns) states that \"Patterns can be nested within each other\" (which is the case here, it's just the type-checking that doesn't use all the type info it has).\n\n## To Reproduce\n\n### Example 1: Result (generic)\n\nHere, I'd expect mypy to narrow the type of `result`, e.g. to `Err[ValueError]` inside the `case Err(ValueError() as val)` block, and to `Never` inside the `case _` block.\n\n```python\nSuccessType = TypeVar(\"SuccessType\")\nFailureType = TypeVar(\"FailureType\")\n\n\nclass Ok(Generic[SuccessType]):\n    __match_args__ = (\"_value\",)\n\n    def __init__(self, value: SuccessType) -\u003e None:\n        self._value = value\n\n\nclass Err(Generic[FailureType]):\n    __match_args__ = (\"_value\",)\n\n    def __init__(self, value: FailureType) -\u003e None:\n        self._value = value\n\n\nResult = Ok[SuccessType] | Err[FailureType]\n\n\ndef handle_result(result: Result[str, ValueError | AttributeError]) -\u003e None:\n    match result:\n        case Ok(success_value):\n            # Revealed type is \"builtins.str\" Mypy\n            reveal_type(success_value)\n            # Revealed type is \"Ok[builtins.str]\" Mypy\n            reveal_type(result)\n        case Err(ValueError() as val):\n            # Revealed type is \"builtins.ValueError\" Mypy\n            reveal_type(val)\n            # Revealed type is \"Err[Union[builtins.ValueError, builtins.AttributeError]]\" Mypy\n            reveal_type(result)\n        case Err(AttributeError()):\n            # Revealed type is \"Err[Union[builtins.ValueError, builtins.AttributeError]]\" Mypy\n            reveal_type(result)\n        case _:\n            # Argument 1 to \"assert_never\" has incompatible type \"Err[ValueError | AttributeError]\"; expected \"Never\" Mypy(arg-type)\n            assert_never(result)\n```\n\n### Example 2: NonGenericErr (non-generic)\n\nHere, I narrowed the scope to matching on the error class, and made it non-generic. Even here, mypy can narrow the attribute (`val: ValueError`), but not the object (`err: NonGenericErr` and `err._value: ValueError | AttributeError`). And doesn't realize in the `case _` block that we've already exhausted all patterns above.\n\n```python\nclass NonGenericErr:\n    __match_args__ = (\"_value\",)\n\n    def __init__(self, value: ValueError | AttributeError) -\u003e None:\n        self._value = value\n\n\ndef handle_non_generic_err(err: NonGenericErr) -\u003e None:\n    # Revealed type is \"NonGenericErr\" Mypy\n    reveal_type(err)\n    match err:\n        case NonGenericErr(ValueError() as val):\n            # Revealed type is \"builtins.ValueError\" Mypy\n            reveal_type(val)\n            # Revealed type is \"Union[builtins.ValueError, builtins.AttributeError]\" Mypy\n            reveal_type(err._value)\n            # Revealed type is \"NonGenericErr\" Mypy\n            reveal_type(err)\n        case NonGenericErr(AttributeError()):\n            # Revealed type is \"NonGenericErr\" Mypy\n            reveal_type(err)\n        case _:\n            # Argument 1 to \"assert_never\" has incompatible type \"NonGenericErr\"; expected \"Never\" Mypy(arg-type)\n            assert_never(err)\n```\n\n### Example 3: FailureResult (generic, dataclass)\n\nI could see the logic that Example 2 is constrained by the lack of a generic type for mypy to use to narrow `err` beyond `NonGenericErr`. But even if we add that back, mypy can't narrow `err` as expected within any of the `case` blocks.\n\nThis example is basically a trimmed down / tighter-scoped version of Example 1.\n\n```python\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass FailureResult[ErrorType]:\n    error: ErrorType\n\n\ndef handle_failure_result(failure_result: FailureResult[ValueError | AttributeError]) -\u003e None:\n    match failure_result:\n        case FailureResult(ValueError() as error):\n            # Revealed type is \"builtins.ValueError\" Mypy\n            reveal_type(error)\n            # Revealed type is \"Union[builtins.ValueError, builtins.AttributeError]\" Mypy\n            reveal_type(failure_result.error)\n            # Revealed type is \"FailureResult[Union[builtins.ValueError, builtins.AttributeError]]\" Mypy\n            reveal_type(failure_result)\n        case FailureResult(AttributeError()):\n            # Revealed type is \"FailureResult[Union[builtins.ValueError, builtins.AttributeError]]\" Mypy\n            reveal_type(failure_result)\n        case _:\n            # Argument 1 to \"assert_never\" has incompatible type \"FailureResult[ValueError | AttributeError]\"; expected \"Never\" Mypy(arg-type)\n            assert_never(failure_result)\n```\n\n## Expected Behavior\n\nMypy successfully narrows the type of an object we're pattern matching on, based on how we've matched on its attribute, allowing for an exhaustive `match` statement ending with `assert_never` if we have indeed exhausted all possible patterns.\n\n## Actual Behavior\n\nSee errors and unexpected `reveal_type` outputs above\n\n## Your Environment\n\n- Mypy version used: mypy 1.15.0\n- Mypy configuration options from `mypy.ini` (and other config files):\n\u003cdetails\u003e\u003csummary\u003e`mypy.ini`\u003c/summary\u003e\n\n```ini\n[mypy]\npython_version = 3.13\nmypy_path = typings\nignore_missing_imports = True\ncheck_untyped_defs = True\ndisallow_untyped_defs = True\ndisallow_untyped_calls = True\nstrict_equality = True\ndisallow_any_unimported = True\nwarn_return_any = True\nno_implicit_optional = True\npretty = True\nshow_error_context = True\nshow_error_codes = True\nshow_error_code_links = True\nno_namespace_packages = True\n```\n\u003c/details\u003e\n- Python version used: 3.13\n\n---\n\nThanks for all the work done to make mypy what it is!\n","author":{"url":"https://github.com/alythobani","@type":"Person","name":"alythobani"},"datePublished":"2025-05-12T18:47:21.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":3},"url":"https://github.com/19081/mypy/issues/19081"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:17d58c04-dd3c-db6a-cb91-81fa0dabd718
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC81E:CB088:2730631:385E71D:6A57BB4B
html-safe-noncece34dfaabd0381beb71f37c370255367a1e4adf04df662b8ec70609ce908c62c
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDODFFOkNCMDg4OjI3MzA2MzE6Mzg1RTcxRDo2QTU3QkI0QiIsInZpc2l0b3JfaWQiOiIyNTcyNDk3MTAzNTQyMDA4NjUxIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmacd6777adcb3d8f87f9b287f546136a7053ce92fd4dfbf682135ff47e0f6f89ea3
hovercard-subject-tagissue:3057837935
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/mypy/19081/issue_layout
twitter:imagehttps://opengraph.githubassets.com/56643b9adc2e680d6ca70b082cd6f4acf105432559a94c981a03b23ea566c29c/python/mypy/issues/19081
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/56643b9adc2e680d6ca70b082cd6f4acf105432559a94c981a03b23ea566c29c/python/mypy/issues/19081
og:image:altBug Report Summary TLDR Mypy doesn't narrow a parent object's type when subpattern-matching on one of its attributes. Longer summary Mypy doesn't always use attribute sub-pattern matches (e.g. case...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamealythobani
hostnamegithub.com
expected-hostnamegithub.com
None899c314dfde9abcf8fc1fe8c04f09866b347ea06f43166d653afc482795c9fca
turbo-cache-controlno-preview
go-importgithub.com/python/mypy git https://github.com/python/mypy.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id7053637
octolytics-dimension-repository_nwopython/mypy
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id7053637
octolytics-dimension-repository_network_root_nwopython/mypy
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
release67aa73f3bba9e68b2de0ebe01c65fcd120461cba
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/mypy/issues/19081#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fmypy%2Fissues%2F19081
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
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%2Fmypy%2Fissues%2F19081
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%2Fmypy
Reloadhttps://github.com/python/mypy/issues/19081
Reloadhttps://github.com/python/mypy/issues/19081
Reloadhttps://github.com/python/mypy/issues/19081
Please reload this pagehttps://github.com/python/mypy/issues/19081
python https://github.com/python
mypyhttps://github.com/python/mypy
Please reload this pagehttps://github.com/python/mypy/issues/19081
Notifications https://github.com/login?return_to=%2Fpython%2Fmypy
Fork 3.2k https://github.com/login?return_to=%2Fpython%2Fmypy
Star 20.5k https://github.com/login?return_to=%2Fpython%2Fmypy
Code https://github.com/python/mypy
Issues 2.7k https://github.com/python/mypy/issues
Pull requests 463 https://github.com/python/mypy/pulls
Actions https://github.com/python/mypy/actions
Projects https://github.com/python/mypy/projects
Wiki https://github.com/python/mypy/wiki
Security and quality 0 https://github.com/python/mypy/security
Insights https://github.com/python/mypy/pulse
Code https://github.com/python/mypy
Issues https://github.com/python/mypy/issues
Pull requests https://github.com/python/mypy/pulls
Actions https://github.com/python/mypy/actions
Projects https://github.com/python/mypy/projects
Wiki https://github.com/python/mypy/wiki
Security and quality https://github.com/python/mypy/security
Insights https://github.com/python/mypy/pulse
Mypy doesn't narrow a matched object's type (generic or not) based on attribute subpattern matchhttps://github.com/python/mypy/issues/19081#top
bugmypy got something wronghttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22bug%22
topic-match-statementPython 3.10's match statementhttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22topic-match-statement%22
topic-type-narrowingConditional type narrowing / binderhttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22topic-type-narrowing%22
https://github.com/alythobani
alythobanihttps://github.com/alythobani
on May 12, 2025https://github.com/python/mypy/issues/19081#issue-3057837935
attribute sub-pattern matcheshttps://peps.python.org/pep-0636/#matching-positional-attributes
poltergeist's Result = Ok[_T] | Err[_E] typehttps://github.com/alexandermalyga/poltergeist/blob/main/poltergeist/result.py
PEP 636 – Structural Pattern Matching: Tutorialhttps://peps.python.org/pep-0636/#composing-patterns
bugmypy got something wronghttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22bug%22
topic-match-statementPython 3.10's match statementhttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22topic-match-statement%22
topic-type-narrowingConditional type narrowing / binderhttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22topic-type-narrowing%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.