Opened 3 weeks ago

Closed 3 weeks ago

Last modified 3 weeks ago

#37494 closed Cleanup/optimization (wontfix)

Document that RunPython callables receive a StateApps instance

Reported by: Thibaut Decombe Owned by:
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The ​`RunPython` docs say the first argument passed to code / reverse_code is "an instance of django.apps.registry.Apps containing historical models".
At runtime it is a django.db.migrations.state.StateApps (see django/db/migrations/operations/special.py, ​RunPython.database_forwards().

This difference matters to users who follow the docs literally, especially when annotating migration functions:

def forwards(apps: Apps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    Person = apps.get_model("myapp", "Person")

Apps is also the type of the global registry (django.apps.apps), whose get_model() returns the current models from models.py.

With the documented annotation, tools such as the django-stubs mypy plugin can't tell this historical registry apart from the global one. They resolve get_model() to the current model class, which may have different fields than the historical model (​https://github.com/typeddjango/django-stubs/issues/3584).

Proposal: mention django.db.migrations.state.StateApps (as a subclass of Apps) in the RunPython docs.

Change History (3)

comment:1 by Thibaut Decombe, 3 weeks ago

Has patch: set

comment:2 by Sarah Boyce, 3 weeks ago

Resolution: → wontfix
Status: new → closed

So, looks like the existing wording predates the introduction of StateApps in a159b1facd222c20dde12f1e0117643af528d511, but because StateApps is a subclass of Apps - I think this is fine?
StateApps feels like an undocumented implementation detail, not part of Django's public API. I don't think we should make it public specifically to accommodate type annotations.

comment:3 by Hugo Osvaldo Barrera, 3 weeks ago

While StateApps is _technically_ a subclass of Apps (from a purely pedantic point of view), it has diverging behaviour, returning different types. It violates the Liskov substitution principle, so treating at as a "regular" subclass isn't entirely right.

It's also not an internal implementation detail: it's returned by a publicly documented interface and users are expected to use it.

Note: See TracTickets for help on using tickets.
Back to Top