I am trying to pass **kwargs
to another function but only if it is not null. Right now I have this if else
and I am wondering if there is a more efficient more pythonic way?
if other:
html.append(self.render_option(val, label, selected, **other))
else:
html.append(self.render_option(val, label, selected))
If other is NoneType
then I get the error:
...argument after ** must be a mapping, not NoneType
Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .
Summary. Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. 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.
First of all, let me tell you that it is not necessary to write *args or **kwargs. Only the * (asterisk) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention.
Functions Accepting Any Number of Keyword Arguments You can change this default behavior by declaring positional-only arguments or keyword-only arguments. When defining a function, you can include any number of optional keyword arguments to be included using kwargs , which stands for keyword arguments.
I would use either
html.append(self.render_option(val, label, selected, **(other or {})))
or
html.append(self.render_option(val, label, selected, **(other if other is not None else {})))
or the more explicit
if other is None:
other = {}
html.append(self.render_option(val, label, selected, **other))
Passing an empty dict as kwargs should be the same as not specifying kwargs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With