50

Here is an example of what I'm trying to achieve. The desired effect is that a particular feature should take effect if and only if its relevant setting exists is defined. Otherwise, the feature should be disabled.

settings.py:

SOME_VARIABLE = 'some-string'
ANOTHER_VARIABLE = 'another-string'

random_code_file.py:

from django.conf import settings

if settings.is_defined('ANOTHER_VARIABLE'): # <- I need this.
    do_something(settings.ANOTHER_VARIABLE)
else:
    do_something_completely_different()

In the code above, I'm missing whatever I should do instead of settings.is_defined.

If this is the wrong approach to the problem altogether, I'd be happy to hear about alternative approaches as well. The desired effect is an auto-activated feature which only takes effect if the relevant setting exists. I would prefer avoiding some special settings.ACTIVE_FEATURES setting or a special value such as a blank string or None for the feature to assess whether it is to take effect or not.

The last thing I'd like to do is to use try/except. I'd rather go for an empty value indicating exclusion of the feature. - But if try/except-ing it is really the preferred method, I will mark the answer as correct if exhaustive sources or explanations are provided. In fact that goes for any answer.

So in short, I need the proper way to check if a settings variable is defined in Django.

Thanks in advance!

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
Teekin
  • 12,581
  • 15
  • 55
  • 67
  • 2
    Why is this specific to Django? I believe that there is a built-in Python method that allows you to do this – nmagerko Jul 24 '14 at 01:23
  • 1
    I assumed that the 'settings' object was unique to Django. I don't suppose you could have educated me on how to do this in Python generally? :) – Teekin Jul 24 '14 at 10:38

1 Answers1

92

It seemed you've made it the correct way: import setting object and check.

And you can try to use:

if hasattr(settings, 'ANOTHER_VARIABLE'):

instead of:

if settings.is_defined('ANOTHER_VARIABLE'):

I found the documentation, hope this might help.

Laban
  • 2,304
  • 1
  • 14
  • 15
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
  • 3
    From the docs: ["Note that `django.conf.settings` isn’t a module – it’s an object."](https://docs.djangoproject.com/en/3.1/topics/settings/#using-settings-in-python-code). – djvg Jan 28 '21 at 20:05