Configuring an object via a dictionary

Tobiah toby at tobiah.org
Fri Mar 15 14:59:20 EDT 2024


On 3/15/24 02:30, Loris Bennett 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']

> 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?

class Foo():

         def __init__(self, config):

                 for key, val in config.iteritems():
                         setattr(self, key, val)

f = Foo({'cat': 'dog'})

print(f.cat)

(outputs 'dog')



More information about the Python-list mailing list