Configuring an object via a dictionary

Thomas Passin list1 at tompassin.net
Fri Mar 15 14:45:21 EDT 2024


On 3/15/2024 5:30 AM, Loris Bennett via Python-list wrote:
> Hi,
> 
> I am initialising an object via the following:
> 
>      def __init__(self, config):
> 
>          self.connection = None
> 
>          self.source_name = config['source_name']
>          self.server_host = config['server_host']
>          self.server_port = config['server_port']
>          self.user_base = config['user_base']
>          self.user_identifier = config['user_identifier']
>          self.group_base = config['group_base']
>          self.group_identifier = config['group_identifier']
>          self.owner_base = config['owner_base']
> 
> However, some entries in the configuration might be missing.  What is
> the best way of dealing with this?
> 
> I could of course simply test each element of the dictionary before
> trying to use.  I could also just write
> 
>         self.config = config
> 
> but then addressing the elements will add more clutter to the code.
> 
> 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?
> 
> Or should I be doing this completely differently?

         self.source_name = config.get('source_name', default_value)

Or, if you like this kind of expression better,

         self.source_name = config.get('source_name') or default_value

.get() will return None if the key doesn't exist, or the default value 
if you specify one.


More information about the Python-list mailing list