kwargs parsing best practice

20,787

Solution 1

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.

Solution 2

If the key provided in get() is not in the dictionary the result is None.

self.log = kwargs.get('log')
self.bin = kwargs.get('bin')
self.pid = kwargs.get('pid')
self.conf = kwargs.get('conf')

Solution 3

for k,v in kwarg.iteritems():
   setattr(self, k, v)

In which setattr(self, "bin", "val") is like calling self.bin = "val"

However it is more desirable to have a whitelist like @Sven Marnach has.

Solution 4

for k,v in kw.items():
   setattr(self, k, v)
Share:
20,787

Related videos on Youtube

nnachefski
Author by

nnachefski

Updated on July 09, 2022

Comments

  • nnachefski
    nnachefski almost 2 years

    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]
    
  • pajton
    pajton about 13 years
    Nice! Could be even shorter with default value: for key in (...): setattr(self, key, kwargs.get(key))
  • Sven Marnach
    Sven Marnach about 13 years
    @pajton: Of course, but I tried to stay as close to the OP's code as possible.
  • Shashank Sawant
    Shashank Sawant almost 8 years
    @pajton Why is the if key in kwargs: line removed in your suggestion? Why not check if key in kwargs?
  • pajton
    pajton almost 8 years
    It's not needed if it's OK to have a default value for these params. kwargs.get(key) will return None if the key is not present
  • Yuri Feldman
    Yuri Feldman over 5 years
    There's also kwargs.pop(key[, default]) when kwargs are to be forwarded to internal calls. This one raises a key error though if key not found and default not given, so kwargs.pop(key, None) makes sense
  • Valentyn
    Valentyn over 4 years
    @SvenMarnach I like the first example but how do I achieve the same functionality if I have a standalone function? I don't have self defined, hence I get an error ' setattr(self, key, kwargs[key]) NameError: name 'self' is not defined"
  • Sven Marnach
    Sven Marnach over 4 years
    @Valentyn For a simple function, you don't need to assign the arguments to fields in self, so the whole question makes little sense for that case. I would definitely go with defaults for the arguments in that case, like in the last example, just without the assignments.

Related