Opened 44 minutes ago
#37484 new Cleanup/optimization
Avoid importing ctypes at import time in django.core.files.locks on Windows
| Reported by: | Alexandre Zollinger Chohfi | Owned by: | |
|---|---|---|---|
| Component: | Core (Other) | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
On Windows, django/core/files/locks.py imports ctypes and ctypes.wintypes and defines the OVERLAPPED structure and the LockFileEx/UnlockFileEx prototypes at module level. The module is imported by django.core.cache.backends.filebased, which django.core.checks imports, so every import django.db.models on Windows imports ctypes and loads _ctypes.pyd, libffi and the OLE DLLs _ctypes links against, whether or not anything ever locks a file. On other platforms the module only imports fcntl.
Measured on Windows 11 with Python 3.14.4 and Django main (8e3dec6):
python -X importtime -c "import django.db.models": django.core.files.locks takes 11.2 ms cumulative on Windows (0.1 ms on Linux, same machine under WSL2).- Building the ctypes objects on the first lock()/unlock() call instead:
import django.db.modelsis 6.0 ms faster (310.7 -> 300.9 ms, 95% CI 1.2-13.6 ms, 60 alternating runs timed inside the process).
The constants and the lock/unlock functions stay at module level, so the public behavior is unchanged. runtests.py files cache file_storage passes on Windows with the change.
I'd be happy to submit the patch.
AI disclosure: the patch was prepared with GitHub Copilot (Claude Opus 5.5 model), which was used to find the import, and write the patch.