Skip to content

Commit 4dd40fc

Browse files
committed
Avoid importing django.test package when not testing
Importing anything `rest_framework` causes `django.test` to be imported. This is because DRF registers a receiver on the `django.test_signals.setting_changed` signal. This is not really a problem, but it is good to avoid this because it bloats the memory with unnecessary modules (e.g. `django.test`, `django.core.servers.basehttp`, `socketserver`) and increases the startup time. It also doesn't feel right to import test code into non-test code. Try to import the signal from a core module if possible. Note that there's another `django.test` import in `MultiPartRenderer`, however this import is done lazily only if the functionality is used so can be easily avoided.
1 parent 1fd268a commit 4dd40fc

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

rest_framework/settings.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,15 @@
1919
back to the defaults.
2020
"""
2121
from django.conf import settings
22-
from django.test.signals import setting_changed
2322
from django.utils.module_loading import import_string
2423

24+
# Import `setting_changed` from the core package instead of its official
25+
# location if possible, to avoid importing the test module unnecessarily.
26+
try:
27+
from django.core.signals import setting_changed
28+
except ImportError:
29+
from django.test.signals import setting_changed
30+
2531
from rest_framework import ISO_8601
2632

2733
DEFAULTS = {

0 commit comments

Comments
 (0)