Вопрос

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
Это было полезно?

Решение

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.

Другие советы

This is really a comment, but it requires formatting and is too big to fit in a comment.

I suggested:

Why are you worried about it? Just pass them; you don't get an error if there are none, do you?

The response was:

I do get an error if other is none: argument after ** must be a mapping, not NoneType

Counter-example

def print_kwargs(**kwargs):
  for k in kwargs:
    print k, " => ", kwargs[k]

def kwargs_demo(a, **kwargs):
  print a
  print_kwargs(**kwargs)

kwargs_demo(1)
kwargs_demo(99, **{'cat':'dog', 'ice':'cream'})

Output

1
99
ice  =>  cream
cat  =>  dog

Reconnecting the disconnect?

There must be a disconnect between what you're doing and what I think you're doing (and what it appears your question title is asking about). I can generate the error you see with the call to kwargs_mark2() in the code below:

def kwargs_mark2(a):
  print a
  other = None
  print_kwargs(**other)  # Fails with 'must be a mapping, not NoneType'

kwargs_mark2(24)

The fix is fairly straight-forward (and illustrated in kwargs_mark3()): don't create a None object when a mapping is required — create an empty mapping.

def kwargs_mark3(a):
  print a
  other = {}
  print_kwargs(**other)

kwargs_mark3(37)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top