Re: Configuring an object via a dictionary

Liste des GroupesRevenir à cl python 
Sujet : Re: Configuring an object via a dictionary
De : ajm (at) *nospam* flonidan.dk (Anders Munch)
Groupes : comp.lang.python
Date : 18. Mar 2024, 14: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


Date Sujet#  Auteur
15 Mar 24 * Configuring an object via a dictionary15Loris Bennett
15 Mar 24 +- Re: Configuring an object via a dictionary1Mats Wichmann
15 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
15 Mar 24 +* Re: Configuring an object via a dictionary4Tobiah
15 Mar 24 i`* Re: Configuring an object via a dictionary3Tobiah
18 Mar 24 i `* Re: Configuring an object via a dictionary2Loris Bennett
19 Mar 24 i  `- Re: Configuring an object via a dictionary1Pokemon Chw
15 Mar 24 +- Re: Configuring an object via a dictionary1Grant Edwards
15 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
15 Mar 24 +- Re: Configuring an object via a dictionary (Posting On Python-List Prohibited)1Lawrence D'Oliveiro
15 Mar 24 +- Re: Configuring an object via a dictionary12QdxY4RzWzUUiLuE
16 Mar 24 +- Re: Configuring an object via a dictionary1dn
16 Mar 24 +- Re: Configuring an object via a dictionary1Thomas Passin
16 Mar 24 +- Re: Configuring an object via a dictionary1<avi.e.gross
18 Mar 24 `- Re: Configuring an object via a dictionary1Anders Munch

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal