From Django - Difference between import django.conf.settings and import settings, I understand the accepted way to import the settings file:
from django.conf import settings
I've also read Good or bad practice in Python: import in the middle of a file. One of the answers there takes you to http://mail.python.org/pipermail/python-list/2001-July/699176.html, where points #2 and #4 are relevant to my question.
Let's say I have a huge settings.py and throughout my Django code, I only need to use a "lowly" constant like MEDIA_ROOT in one rarely-called method. So, it seems incredibly wasteful to import the entire settings.py:
from django.conf import settings
...
def foo():
my_media_root = settings.MEDIA_ROOT
when I can just import the one needed constant:
from settings import MEDIA_ROOT
...
def foo():
my_media_root = MEDIA_ROOT
and therefore avoid importing the huge settings.py, especially since it may never even be used, if my_media_root is used in only one out of many methods in that file. Of course, this is bad practice, but the "good practice version" of this doesn't work:
from django.conf.settings import MEDIA_ROOT
...
def foo():
my_media_root = MEDIA_ROOT
as, by design, it causes the expected ImportError: No module named settings
exception.
So, my question is, what is the proper way to import just one constant from a large settings.py? Thanks in advance.
If this is a Django project, then the settings file has already been imported, it doesn't cost you anything to simply import it and use the constant you want. Importing a module many times in Python only executes the file once.
The usual way to import settings:
from django.conf import settings
This just assigns one name in your module (settings
) to the value of an existing already-imported settings object. It's equivalent to, and has about the same execution time as:
settings = sys.modules['django.conf'].settings
Have you found problems doing it the simple way?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With