Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kwargs parsing best practice

People also ask

How do you beat Kwargs?

Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter. Always place the **kwargs parameter at the end of the parameter list, or you'll get an error.

Should I use Kwargs?

Avoid them if possible. Note that args and kwargs are just named by convention. You can name them whatever you like. It is the asterisks * and ** that make them powerful.

Can you have Kwargs without args?

Python is pretty flexible in terms of how arguments are passed to a function. The *args and **kwargs make it easier and cleaner to handle arguments. The important parts are “*” and “**”. You can use any word instead of args and kwargs but it is the common practice to use the words args and kwargs.

Why is Kwargs empty?

That dictionary is empty because you have not passed any kwargs in foo1. Note that you should only use variable x and y. Any other variables will cause error.


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.


self.log = kwargs.get('log', default_log)
self.bin = kwargs.get('bin', default_bin)
self.pid = kwargs.get('pid', default_pid)
self.conf = kwargs.get('conf', default_conf)

This has the additional advantage that self.log is assigned in any case (AttributeError means your code is broken as hell, nothing more. Always make sure everything is always assigned.). Without extra self.log = default_log lines. You can omit the default to get None.


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')

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.


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