Configuring an object via a dictionary

Anders Munch ajm at flonidan.dk
Mon Mar 18 09:57:57 EDT 2024


dn wrote:
>Loris Bennett wrote:
>> However, with a view to asking forgiveness rather than
>> permission, is there some simple way just to assign the dictionary
>> elements which do in fact exist to self-variables?
>
>Assuming config is a dict:
>
>	self.__dict__.update( config )

Here's another approach:

config_defaults = dict(
     server_host='localhost',
     server_port=443,
    # etc.
)
...
        def __init__(self, config):
            self.conf = types.SimpleNamespace(**{**config_defaults, **config})

This gives you defaults, simple attribute access, and avoids the risk of name collisions that you get when updating __dict__.

Using a dataclass may be better:

@dataclasses.dataclass
class Settings:
     group_base : str
     server_host : str = 'localhost'
     server_port : int = 443
...
        def __init__(self, config):
            self.conf = Settings(**config)

regards, Anders



More information about the Python-list mailing list