AttributeError: 'Settings' object has no attribute <class that I defined inside settings.py> when settings imported from conf

Question:

I’ve added enum in the settings.py file

class Syncs(Enum):
    A = 'a'
    B = 'b'

when I try to use them in an app by importing from django.conf import settings, it raises:

AttributeError: 'Settings' object has no attribute Syncs

on the other hand if I import settings file directly it works

I know it’s because from django.conf import settings works differently so that’s why this doesn’t work.
Is there some recommended way to do this?

So far I do:

class Syncs(Enum):
    A = 'a'
    B = 'b'

SYNCS = Syncs
Asked By: Milano

||

Answers:

In essence, the settings object is a lazy object that gets populate from the settings module. It will only populate with items that are written in uppercase (can be with punctuations like an underscore). Indeed, the source code that populates the itemsĀ [GitHub] says:

for setting in dir(global_settings):
    if setting.isupper():
        setattr(self, setting, getattr(global_settings, setting))

It will thus check if the setting satisfies the str.isupper() methodĀ [Python-doc], if that is the case, it is added to the object, otherwise it is not. So you will need to define this in all-caps. The rationale behind it is likely that settings are constants, and in Python the convention is that constants are written in all-caps snake-case.

You can define the enum as:

class SYNCS(Enum):
    A = 'a'
    B = 'b'

But it makes me wondering why you want to define an enum in the settings, this is a bit "odd".

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.