kwargs parsing best practice

nnachefski picture nnachefski · Apr 11, 2011 · Viewed 17.8k times · Source

Is there a more compact/efficient way of doing this?

    for key in kwargs:
        if key == 'log':
            self.log = kwargs[key]
        elif key == 'bin':
            self.bin = kwargs[key]
        elif key == 'pid':
            self.pid = kwargs[key]
        elif key == 'conf':
            self.conf = kwargs[key]

Answer

Sven Marnach picture Sven Marnach · Apr 11, 2011

To achieve exactly what you asked for, you could use

for key in ('log', 'bin', 'pid', 'conf'):
    if key in kwargs:
        setattr(self, key, kwargs[key])

or

self.__dict__.update((key, kwargs[key])
                     for key in ('log', 'bin', 'pid', 'conf')
                     if key in kwargs)

However, I would generally prefer something like this:

def f(log=None, bin=None, pid=None, conf=None):
    self.log = log
    self.bin = bin
    self.pid = pid
    self.conf = conf

While this is still somewhat repetitive, the code is really easy to read. All attributes are intialized regardles of whether the corresponding keyword argument is passed in, and the signature of the function clearly documents the arguments and there defaults.