Custom Django Settings and Default Values
This article is more about basic Python than anything else, but I hope it will help some newbies out there get further along faster. I should note that I learned Python by learning Django, so I don't exactly have the best foundation in Python. I think it's getting better though :)
Anyway, there are many occasions when I find myself creating applications that have custom settings which can be defined in a Django project's settings.py file. Sometimes I want to force the developer to define the setting (such as when a third-party API key is required). Other times I want to have sensible defaults which can easily be overridden by the developer if they desire. I struggled for a while to find an elegant solution for providing such default values for my custom settings.
I first tried something like this:
from django.conf import settings try: MY_CUSTOM_SETTING = settings.MY_CUSTOM_SETTING except AttributeError: MY_CUSTOM_SETTING = 'default value' |
That seemed to work well enough, but it just felt dirty to me. After a while of doing thing that way, I started doing it like this:
from django.conf import settings if hasattr(settings, 'MY_CUSTOM_SETTING'): MY_CUSTOM_SETTING = settings.MY_CUSTOM_SETTING else: MY_CUSTOM_SETTING = 'default value' |
Despite being essentially the same, it felt slightly better than the try..except method. I think I stuck with this method for a bit longer than the first method I mentioned. Finally, I found out that Python's built-in getattr function allows you to specify a default value if it fails to retrieve the value of the attribute you want:
from django.conf import settings MY_CUSTOM_SETTING = getattr(settings, 'MY_CUSTOM_SETTING', 'default value') |
So far, this is the most elegant and efficient method I've found for allowing custom settings with default values. Perhaps there is a better way, and I'd be delighted if someone would enlighten me and the rest of the readers.