Sujet : Re: Configuring an object via a dictionary
De : ajm (at) *nospam* flonidan.dk (Anders Munch)
Groupes : comp.lang.pythonDate : 18. Mar 2024, 15:57:57
Autres entêtes
Message-ID : <mailman.117.1710782734.3452.python-list@python.org>
References : 1 2 3
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