← Back to Pull requests

Resolve field nullability at the call site with `__init__` overloads #3763

Closed
unknown closed this pull request without merging on Nov 19, 2026 00:05 UTC
View on GitHub
unknown unknown commented on Oct 25, 2026 22:34 UTC
Author

[!IMPORTANT]

_pyi_private_set_type / _pyi_private_get_type are removed: custom models.Field subclasses now

declare PEP 696 defaults on their type variables and __init__ overloads.

See How to type a custom models.Field?.

I have made things!

Another attempt at this (hopefully the last one!). Each concrete field now declares two __init__ overloads:

  • a null: Literal[True] one annotating self with the nullable specialisation (typing spec, Constructors › __init__)

  • and a fallback keeping the class defaults.


  • The _pyi_private_set/get_type hints are removed from the stubs. Note that some external tools used them:
  • pyrefly and zuban build django support on it, but the current approach has precedence so it's still working. They should however be able to drop custom code so I'll probably open followup issues later.

  • a few package like django-mysql that will have to migrate too. I'll open mr to help them migrate later
  • A few notable side effects of this change that probably need a release note mention:


  • x: models.IntegerField = models.IntegerField(null=True) is now rejected: a bare annotation means the non-null defaults. _These annotation should not be needed so the fix is to drop them (or add explicit type vars)._

  • A bad kwarg on a field constructor now reports call-overload instead of arg-type, so existing # type: ignore[arg-type] on such calls become unused _and need to be migrated to # type: ignore[call-overload]_
  • <details>
    <summary>Smoke test all checker on core features</summary>

    pyrefly 1.4.0, pyright 1.1.414, ty 0.0.90, mypy 2.4.0, zuban 0.10.1 in mypy mode with its Django emulation active.

    class HTMLField(models.TextField): ...
    
    
    _ST = TypeVar("_ST", contravariant=True, default=float | int | str)
    _GT = TypeVar("_GT", covariant=True, default=int)
    
    
    class GenericInt(models.IntegerField[_ST, _GT]): ...
    

    | | requirement | pyrefly | pyright | ty | mypy | mypy + plugin | zuban |
    |---|---|:-:|:-:|:-:|:-:|:-:|:-:|
    | R01 | IntegerField() reads as int | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R02 | IntegerField() rejects writing None | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R03 | IntegerField(null=True) reads as int \| None | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R04 | IntegerField(null=True) accepts writing None | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R05 | IntegerField() accepts writing "12" (Django coerces) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R06 | IntegerField[bool, bool]() reads as bool | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R17 | IntegerField(nul=True) is rejected | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R07 | HTMLField() reads as str | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R08 | HTMLField(null=True) is not an error | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R09 | HTMLField(null=True) reads as str \| None | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ |
    | R18 | x: HTMLField = HTMLField(null=True) accepted | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
    | R10 | GenericInt() reads as int | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R11 | GenericInt(null=True) reads as int \| None | ✅ | ❌¹ | ✅ | ❌¹ | ✅ | ✅ |
    | R12 | RecipeInt() reads as int | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R13 | RecipeInt(null=True) reads as int \| None | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R14 | f: Field[X \| None, Y \| None] = IntegerField(null=True) accepted | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
    | R15 | f: Field[X, Y] = IntegerField(null=True) rejected | ❌² | ✅ | ❌³ | ✅ | ✅ | ❌² |
    | R16 | f: Field = IntegerField() reads as Any | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |

    R09 is the one design limit: a bare non-generic subclass is pinned to TextField[str, str], so stubs alone cannot make it nullable; only the plugin can. The other red cells are checker gaps:

    1. pyright and mypy apply the PEP 696 defaults before matching the inherited self-annotated overload, so GenericInt(null=True) keeps the non-null defaults. The spec says defaults apply only to type variables left unsolved. The documented recipe (R13) passes everywhere.
    2. pyrefly and zuban do not report a nullable field assigned to a non-null Field[X, Y] annotation, although _GT is covariant.
    3. ty accepts it by design since 0.0.99 (the rest of the table was run on 0.0.90): it specialises the call from the declared type, so the field keeps the non-null Field[X, Y] and reads X. See astral-sh/ty#4977, closed as working as intended.

    </details>

    Related issues

    Fixes #766
    Fixes #1264
    Fixes #2724
    Addresses #2043 through the README recipe
    Improves #579
    Supersedes #3317 and #1900

    AI Policy


  • I have read and agree to the AI Policy, removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
  • Followups


  • FK overloads, see https://github.com/typeddjango/django-stubs/pull/3763#discussion_r4380082472

  • FilePathField with concrete str defaults and the same overloads, together with the other fields still reading as Any (RasterField, HStoreField, GeometryField), see https://github.com/typeddjango/django-stubs/pull/3763#discussion_r4444671814. They are Any on master too, so this PR keeps parity.

  • pyrefly issue, so its Django support (pyrefly/lib/alt/class/django.rs) works from the stubs' type parameters:

  • - [x] Read a field's set/get types from its type parameter defaults instead of _pyi_private_set_type/_pyi_private_get_type. The implicit id only goes through these hints (it reads Unknown without them), so AutoField keeps them until then.
    - [x] Match the set/get type parameters by position, or by mapping them to Field's own, instead of the literal names _ST/_GT (_To/_Through for M2M). The _contra/_co rename in #3784 already breaks explicit arguments like IntegerField[bool, bool] on master, and the per-field names here (_ST_Int_contra, ...) would too.
    - [x] Keep folding None in on null=True when the types come from the type parameters: bare subclasses (class HTMLField(TextField)), generic subclasses whose type vars have no defaults and JSONField lose it without the hints.
    - [x] Report a nullable field assigned to a non-null Field[X, Y] annotation, or overriding one (is_active = BooleanField(null=True) on an AbstractUser subclass).
  • zuban issue so it can drop its _pyi_private_-based Django support

  • Migration PRs for django-mysql and the other packages relying on _pyi_private_

  • delete unnecessary plugin code
  • [!TIP]

    Review commit per commit should be a lot easier

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: UnknownPlatypus Review duration: 34651m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #3763"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%