0

I very often come along the need to build statements like this in python:

kwargs['help'] = '' if 'help' not in kwargs else kwargs['help']

and I wonder if this is pythonic way to do this. I dont like the repetitive else part, but if I do

if 'help' not in kwargs:
    kwargs['help'] = ''

this would be less repetitive but not really less verbose because its on two lines. And I really like in the first example, that it starts with the var assignment (which is the important thing that is happening here)

The problem is, I cant work with the and/or shortcircuiting when assigning variables

var or var = ''

wont work.

I would love to have something simple like:

var = '' if not var

so just without the else statement. But this is not implemented in python, so would be my way (first example) be considered pythonic, or should I use the two line if clause?

Asara
  • 2,791
  • 3
  • 26
  • 55

3 Answers3

2

The simplest way of handling the kwargs issues is a one-liner:

kwargs.setdefault('help', '')

setdefault happens to return the value (which you ignore), but it does exactly what you want; nothing if the value is set, set the default otherwise.

For general variables, you can't handle "unsetness" nicely, but if you're trying to set var only if it's falsy, then:

 var = var or ''

will work just fine; or evaluates to the last expression evaluated, so it will produce any truthy value of var by preference, and '' otherwise.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

If you know kwargs is dict you might use .get method, so instead of:

kwargs['help'] = '' if 'help' not in kwargs else kwargs['help']

you might do

kwargs['help'] = kwargs.get('help', '')
Daweo
  • 31,313
  • 3
  • 12
  • 25
0

You can use the setdefault method

kwargs.setdefault('help', '')

or you could use a collections.defaultdict(str).

timgeb
  • 76,762
  • 20
  • 123
  • 145