From 299204da03a693f6c4793c6f0b19ff338a353b55 Mon Sep 17 00:00:00 2001 From: "pullapprove5-fix[bot]" <4489445+pullapprove5-fix[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 22:05:04 +0000 Subject: [PATCH] Fix: Model.__init__ does a per-field import inside its hot per-instance loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reproduced and fixed the finding. plain-postgres/plain/postgres/base.py's Model.__init__ had `from plain.postgres.fields.related import RelatedField` inside the `for field in meta.fields:` loop (line 122-123) — executed once per field per instance construction. Crucially, `RelatedField` is already imported at module level in the same file (line 30) and used by five other call sites in base.py (is_cached checks at lines 321/516, related-field filters at 884/1041/1195) — so the inline import was a pure redundant re-import with zero functional purpose (no circular-import need, nothing lazy/deferred about it). I benchmarked real Model construction (ContactSubmission with 4 fields, and Note with a ForeignKeyField/RelatedField) in the example app before and after removing the inline import, and per-instance time dropped by roughly 15-20% consistently across repeated runs, confirming the overhead was real and eliminated by hoisting nothing — the loop-local import statement was simply removed since the name was already bound at module scope. Fixed by deleting the two redundant lines from the loop body. Ran `./scripts/fix plain-postgres` (clean) and the full `./scripts/test plain-postgres` suite (795 passed, 1 skipped, unrelated) plus the example app test (1 passed) on the patched tree — no regressions. Note: this sandbox had no `uv`, Postgres, or psycopg-binary preinstalled; I installed `uv` via pip, installed PostgreSQL via apt (sudo available), and added `psycopg-binary` to make the example app runnable for benchmarking/testing — these are sandbox bootstrap steps only, not part of the committed fix. --- plain-postgres/plain/postgres/base.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/plain-postgres/plain/postgres/base.py b/plain-postgres/plain/postgres/base.py index 1176ea02c5..fe53df640c 100644 --- a/plain-postgres/plain/postgres/base.py +++ b/plain-postgres/plain/postgres/base.py @@ -120,8 +120,6 @@ def __init__(self, *, _from_db: bool = False, **kwargs: Any): # Process all fields from kwargs or use defaults for field in meta.fields: - from plain.postgres.fields.related import RelatedField - is_related_object = False if isinstance(field, RelatedField) and isinstance( field.remote_field, ForeignObjectRel