Afelium
Afelium

Reputation: 65

Dynaconf: how to set a key's default value for all elements in array

consider the following configuration file:

#settings.toml

default_datapath = "/data"

[[hosts]]
address = "192.168.10.4"
name = "foo"

[[hosts]]
address = "192.168.10.5"
name = "bar"

#...other hosts with no specified datapath...

[[hosts]]
address = "192.168.10.32"
name = "baz"
datapath = "/custom/data" #uses a custom datapath

How do I make it so that for all elements of the array, settings.hosts[i].datapath returns the key's value if present, else default_datapath?

I've taken a look at validators with default values, but there doesn't seem to be a way to apply validators to array elements, else I would've gone for something like this:

#config.py
from dynaconf import Dynaconf, Validator

settings = Dynaconf(settings_files=['settings.toml'])

validators = [
    Validator(f"hosts[{i}].datapath", default=settings.default_datapath) 
    for i in range(len(settings.hosts))
]

settings.validators.register(*validators)
settings.validators.validate()
#DOESN'T WORK

The alternatives are:

Upvotes: 0

Views: 110

Answers (0)

Related Questions