Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass **kwargs if not none

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
like image 566
Johnston Avatar asked May 06 '14 00:05

Johnston


People also ask

How do you pass a Kwargs argument in Python?

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

How do you pass Kwargs to a function?

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.

Can you have Kwargs without args?

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.

Can Kwargs be optional?

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.


1 Answers

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.

like image 91
Peter Gibson Avatar answered Oct 29 '22 23:10

Peter Gibson