René's URL Explorer Experiment


Title: Adding __init__ breaks type inference from __new__ · Issue #12045 · python/mypy · GitHub

Open Graph Title: Adding __init__ breaks type inference from __new__ · Issue #12045 · python/mypy

X Title: Adding __init__ breaks type inference from __new__ · Issue #12045 · python/mypy

Description: Hello, i'm trying to fix a bug in django type stubs, and i believe i've stubled upon bug in mypy. Django has following syntax for defining foreign keys: class Book(models.Model): author = models.ForeignKey(Author, null=True) This means a...

Open Graph Description: Hello, i'm trying to fix a bug in django type stubs, and i believe i've stubled upon bug in mypy. Django has following syntax for defining foreign keys: class Book(models.Model): author = models.Fo...

X Description: Hello, i'm trying to fix a bug in django type stubs, and i believe i've stubled upon bug in mypy. Django has following syntax for defining foreign keys: class Book(models.Model): author = m...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Adding __init__ breaks type inference from __new__","articleBody":"Hello, i'm trying to fix a bug in django type stubs, and i believe i've stubled upon bug in mypy.\r\n\r\nDjango has following syntax for defining foreign keys:\r\n\r\n```python\r\nclass Book(models.Model):\r\n    author = models.ForeignKey(Author, null=True)\r\n```\r\n\r\nThis means author should be `Author | None`.\r\n\r\nRight now django-types are using `@override` for `__init__` with differently typed `self` parameter:\r\n\r\nhttps://github.com/sbdchd/django-types/blob/90fc353b7d05ec600a4807d8b29343a6538692b1/django-stubs/db/models/fields/related.pyi#L293\r\n\r\n```\r\n@overload\r\ndef __init__(\r\n        self: ForeignKey[_M],\r\n       ...\r\n       null: Literal[False],\r\n...\r\n@overload\r\ndef __init__(\r\n        self: ForeignKey[Optional[_M]],\r\n        ...\r\n       null: Literal[True],\r\n...\r\n```\r\n\r\nAnd it works for `mypy`, but doesn't work for `pyright`. In mypy it works becouse it uses undocumented feature of typing self, as i discovered here:\r\n\r\n- https://github.com/microsoft/pyright/issues/2909#issuecomment-1019374993\r\n\r\nProper, and most concise way of doing this, would be overloading `__new__` with args/kwargs and `bool: Literal[...]`, and leaving full annotation with all arguments typed in `__init__` (which i attempted here https://github.com/sbdchd/django-types/pull/86).\r\n\r\nBut, when we try to do this: mypy would ignore overrides in `__new__` and will always use non-optional case.\r\n\r\n**To Reproduce**\r\n\r\nTo reproduce this without much clutter, we can use following code:\r\n\r\n```python\r\n# related_field_minimal.pyi\r\nfrom typing import Generic, Literal, Optional, Type, TypeVar, overload\r\n\r\nclass Model: ...\r\n\r\n_M = TypeVar(\"_M\", bound=Optional[Model])\r\n\r\nclass ForeignKey(Generic[_M]):\r\n    @overload\r\n    def __new__(\r\n        cls,\r\n        to: Type[_M],\r\n        null: Literal[False] = ...,\r\n    ) -> ForeignKey[_M]: ...\r\n    @overload\r\n    def __new__(\r\n        cls,\r\n        to: Type[_M],\r\n        null: Literal[True],\r\n    ) -> ForeignKey[Optional[_M]]: ...\r\n    def __init__(self, to: Type[_M], null: bool) -> None: ...\r\n```\r\n\r\n```python\r\n# models.py\r\nfrom typing import Optional\r\nfrom related_field_minimal import ForeignKey, Model\r\n\r\n\r\nclass Test(Model):\r\n    pass\r\n\r\n\r\nclass BookModel(Model):\r\n    required_field = ForeignKey(to=Test, null=False)\r\n    optional_f1 = ForeignKey(to=Test, null=True)\r\n    optional_f2 = ForeignKey[Test](to=Test, null=True)\r\n    optional_f3 = ForeignKey[Optional[Test]](to=Test, null=True)\r\n\r\nreveal_type(BookModel.required_field)\r\nreveal_type(BookModel.optional_f1)\r\nreveal_type(BookModel.optional_f2)\r\nreveal_type(BookModel.optional_f3)\r\n```\r\n\r\nWhen there is no `__init__` in ForeignKey, inferred types are correct, both in mypy and pyright.\r\n\r\n```\r\nmodels.py:15: note: Revealed type is \"related_field_minimal.ForeignKey[models.Test]\"\r\nmodels.py:16: note: Revealed type is \"related_field_minimal.ForeignKey[Union[models.Test, None]]\"\r\nmodels.py:17: note: Revealed type is \"related_field_minimal.ForeignKey[Union[models.Test, None]]\"\r\nmodels.py:18: note: Revealed type is \"related_field_minimal.ForeignKey[Union[models.Test, None]]\"\r\n```\r\n\r\nAs soon as we add `__init__` to our type definition in `related_field_minimal.pyi`, it becomes incorrect in mypy:\r\n\r\n```\r\nmodels.py:15: note: Revealed type is \"related_field_minimal.ForeignKey[models.Test]\"\r\nmodels.py:16: note: Revealed type is \"related_field_minimal.ForeignKey[models.Test]\"\r\nmodels.py:17: note: Revealed type is \"related_field_minimal.ForeignKey[models.Test]\"\r\nmodels.py:18: note: Revealed type is \"related_field_minimal.ForeignKey[Union[models.Test, None]]\"\r\n```\r\n\r\n(pyright still handles this case correctly).\r\n\r\n**Your Environment**\r\n\r\n- Mypy version used: 0.931\r\n- Mypy command-line flags: None\r\n- Mypy configuration options from `mypy.ini` (and other config files): None\r\n- Python version used: 3.10\r\n","author":{"url":"https://github.com/last-partizan","@type":"Person","name":"last-partizan"},"datePublished":"2022-01-23T10:48:30Z","url":"https://github.com/python/mypy/issues/12045"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:4b25b676-cc46-ec0d-ea52-f2b7feb83690
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE444:197995:237D607:302FD08:6B002D05
html-safe-nonce57ee0a5d9e3712a6457e91c09cfe21225261e9debc0eeab388ff713096ac5351
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNDQ0OjE5Nzk5NToyMzdENjA3OjMwMkZEMDg6NkIwMDJEMDUiLCJ2aXNpdG9yX2lkIjoiODA3MDg0MDAxNDU2MjQwNTYzOCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac80f20a78ebabfe7e8afe395a5044910b40eacdab08a1865ed3c59755e15cfec9
hovercard-subject-tagissue:1111835427
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/12045/issue_layout
twitter:imagehttps://opengraph.githubassets.com/97101d58d9396194f05df7a4e0db629e14a9b4cc72b6f488f451284e918c2f4f/python/mypy/issues/12045
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/97101d58d9396194f05df7a4e0db629e14a9b4cc72b6f488f451284e918c2f4f/python/mypy/issues/12045
og:image:altHello, i'm trying to fix a bug in django type stubs, and i believe i've stubled upon bug in mypy. Django has following syntax for defining foreign keys: class Book(models.Model): author = models.Fo...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamelast-partizan
hostnamegithub.com
expected-hostnamegithub.com
None7d0829bbde9e48b2486cb5dd6d147896eb01d32134627091f818958a935ef3f0
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
releasef3f3a43ca095cdea3abbb394112e971f9fdb94fa
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/mypy/issues/12045#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fmypy%2Fissues%2F12045
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
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
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://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
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fmypy%2Fissues%2F12045
Sign uphttps://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/12045
Reloadhttps://github.com/python/mypy/issues/12045
Reloadhttps://github.com/python/mypy/issues/12045
pythonhttps://github.com/python
mypyhttps://github.com/python/mypy
Codehttps://github.com/python/mypy
Issues2.7k (2.7k)https://github.com/python/mypy/issues
Pull requests547 (547)https://github.com/python/mypy/pulls
Actionshttps://github.com/python/mypy/actions
Projectshttps://github.com/python/mypy/projects
Wikihttps://github.com/python/mypy/wiki
Security and qualityhttps://github.com/python/mypy/security
Insightshttps://github.com/python/mypy/insights
https://github.com/python/mypy
New issuehttps://github.com/login?return_to=https://github.com/python/mypy/issues/12045
New issuehttps://github.com/login?return_to=https://github.com/python/mypy/issues/12045
Adding __init__ breaks type inference from __new__https://github.com/python/mypy/issues/12045#top
bugmypy got something wronghttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22bug%22
https://github.com/last-partizan
last-partizanhttps://github.com/last-partizan
on Jan 23, 2022https://github.com/python/mypy/issues/12045#issue-1111835427
https://github.com/sbdchd/django-types/blob/90fc353b7d05ec600a4807d8b29343a6538692b1/django-stubs/db/models/fields/related.pyi#L293https://github.com/sbdchd/django-types/blob/90fc353b7d05ec600a4807d8b29343a6538692b1/django-stubs/db/models/fields/related.pyi#L293
Invalid typing for __init__ in Generic classes microsoft/pyright#2909 (comment)https://github.com/microsoft/pyright/issues/2909#issuecomment-1019374993
sbdchd/django-types#86https://github.com/sbdchd/django-types/pull/86
last-partizanhttps://github.com/last-partizan
bugmypy got something wronghttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22bug%22
on Jan 23, 2022https://github.com/python/mypy/issues/12045#event-5938044288
https://github.com/stereobutter
stereobutterhttps://github.com/stereobutter
on Apr 8, 2023https://github.com/python/mypy/issues/12045#issuecomment-1500831074
https://github.com/ikonst
ikonsthttps://github.com/ikonst
on Apr 8, 2023https://github.com/python/mypy/issues/12045#issuecomment-1500874275
https://github.com/Mr-Pepe
Mr-Pepehttps://github.com/Mr-Pepe
on Dec 1, 2023https://github.com/python/mypy/issues/12045#issuecomment-1835424074
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/mypy/issues/12045
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/mypy/issues/12045
bugmypy got something wronghttps://github.com/python/mypy/issues?q=state%3Aopen%20label%3A%22bug%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.