user1427661
user1427661

Reputation: 11774

DRYly represent a list of settings objects

I'm sketching out a Django model that has a few different boolean fields:

video_enabled = models.BooleanField()
audio_enabled = models.BooleanField()
sensors_enabled = models.BooleanField()
backup_enabled = models.BooleanField()

I have a number of different 'modes' that have different settings involving these booleans. I'd like to store the 'defaults' for these modes in some kind of dictionary structure so I can easily reset the settings model to a default state based on what mode I want to restore it to. To store those settings, I've been doing something like this:

SETTINGS = { 
    'mode_1': {
        'video': True,
        'audio': True,
        'sensor': True,
        'backup': True
    }
    'mode_2': {
         'video': False,
         'audio': False,
    .... etc. .....

As the number of modes grows, this obviously gets really repetitive.

Is there a nicer, DRYer design pattern that could represent this in Python? I was thinking enums, but I kind of don't want to get locked into an ordered sequence that every component needs to know about in order to communicate with the django server.

Upvotes: 0

Views: 24

Answers (1)

Bakuriu
Bakuriu

Reputation: 101919

If you don't like to always repeat the same keys put them into a list:

keys = ['audio', 'video', 'sensor', 'backup']

SETTINGS = {
    'mode_1': dict.fromkeys(keys, True),
    'mode_2': dict.fromkeys(keys, False),
}

If the default settings may different values then you can still avoid repeating the keys using zip to build the dicts:

SETTINGS = {
    'mode_3': dict(zip(keys, [True, False, False, True])),
}

In fact you could specify the values for each mode and then build the dictionary in a dict comprehension:

import itertools as it
keys = ['audio', 'video', 'sensor', 'backup']

SETTINGS_LIST = (
    ('mode_1', it.repeat(True)), 
    ('mode_2', it.repeat(False)), 
    ('mode_3', [True, False, False, True]),
)

SETTINGS = {mode: dict(zip(keys, values)) for mode, values in SETTINGS_LIST}

This doesn't do any repetition of value or key literal and dict and zip are called only in one place.

Upvotes: 1

Related Questions