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)
Related videos on Youtube
Author by
nnachefski
Updated on July 09, 2022Comments
-
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 about 13 yearsNice! Could be even shorter with default value:
for key in (...): setattr(self, key, kwargs.get(key))
-
Sven Marnach about 13 years@pajton: Of course, but I tried to stay as close to the OP's code as possible.
-
Shashank Sawant almost 8 years@pajton Why is the
if key in kwargs:
line removed in your suggestion? Why not checkif key in kwargs
? -
pajton almost 8 yearsIt's not needed if it's OK to have a default value for these params.
kwargs.get(key)
will returnNone
if the key is not present -
Yuri Feldman over 5 yearsThere'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 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 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.