Search code examples
pythonkeyword-argument

kwargs parsing best practice


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]

Solution

  • 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.