Shouldn't the call to django_stubs_ext.monkeypatch should be inside a TYPE_CHECKING check?
Simple question here about django_stubs_ext. Shouldn't the monkey patching occur only during TYPE_CHECKING ?
Something like this:
# settings.py
if TYPE_CHECKING:
import django_stubs_ext
django_stubs_ext.monkeypatch()
django_stubs_ext.monkeypatch()
should not be placed inside an if TYPE_CHECKING:
block, because it needs to be executed at runtime, not just during type checking.
The purpose of this function is to patch certain Django internals so that mypy
and type hints work correctly. If you wrap it in TYPE_CHECKING
, it will never actually run during program execution — defeating its purpose.
As stated in the official documentation:
“This only needs to be called once, so the call to
monkeypatch
should be placed in your top-level settings.”
Therefore, make sure you call it at the very top of your settings file (or another central entry point) before any django imports.
Here is the link for the reference that I used to answer your question:
https://pypi.org/project/django-stubs-ext/
The example code that is provided in the documentation:
from os import environ
import django_stubs_ext
from split_settings.tools import include, optional
# Monkeypatching Django, so stubs will work for all generics,
# see: https://github.com/typeddjango/django-stubs
django_stubs_ext.monkeypatch()
# Managing environment via `DJANGO_ENV` variable:
environ.setdefault('DJANGO_ENV', 'development')
_ENV = environ['DJANGO_ENV']
_base_settings = (
'components/common.py',
'components/logging.py',
'components/csp.py',
'components/caches.py',
# Select the right env:
'environments/{0}.py'.format(_ENV),
# Optionally override some settings:
optional('environments/local.py'),
)
# Include settings:
include(*_base_settings)