bitgarden
bitgarden

Reputation: 10601

Python: most idiomatic way to set a variable conditionally?

Let's say I have a condition that evaluate a to a boolean, condition, and I want to set the variable foo to a value depending on that condition.

I could write in several different ways (for simplicity, let's assume some_value and some_other_value are constants and not function calls). Here's a way:

foo = None
if condition:
  foo = some_value
else:
  foo = some_other_value

This approach is nice because foo is clearly declared at the top; it is however a bit verbose. We could write it more simply as:

if condition:
  foo = some_value
else:
  foo = some_other_value

This saves us an assignment, but some programmers could find the exact nature of foo's scope unclear.

Another way could be:

foo = some_other_value
if condition:
  foo = some_value

This is more concise and saves us a branch; however it could be misleading for someone quickly reading over the code.

Is one of those ways preferred for style, or execution speed? (although I suspect here the performance gains would be minimal, if not null) Or is another fourth way of writing this code recommended?

Upvotes: 0

Views: 167

Answers (4)

John La Rooy
John La Rooy

Reputation: 304137

Although this can be done with the ternary operator

foo = some_value if condition else some_other_value

Guido never did like the ternary operator, so it can hardly be called "Pythonic"

I think this is the preferred way and compatible with every version of Python out there

if condition:
  foo = some_value
else:
  foo = some_other_value

The difference between that and

foo = some_other_value
if condition:
  foo = some_value

is in the case the some_other_value needs to be computed (by a function say) and you wish to avoid calling the function unnecessarily

Upvotes: 1

Christian Ternus
Christian Ternus

Reputation: 8492

For what it's worth, I prefer the ternary operator:

foo = baz if quux() else bar

But is there a performance reason to prefer one over the other? No.

In [15]: %timeit foo = 2 if random.randint(0,1) else 3
100000 loops, best of 3: 1.69 µs per loop

In [16]: %%timeit
   ....: if random.randint(0,1):
   ....:     foo = 2
   ....: else:
   ....:     foo = 3
   ....:
100000 loops, best of 3: 1.6 µs per loop

In [17]: %%timeit foo = 0
if random.randint(0,1):
    foo = 2
else:
    foo = 3
   ....:
1000000 loops, best of 3: 1.59 µs per loop

Upvotes: 0

ncmathsadist
ncmathsadist

Reputation: 4891

Python has a ternary operator

foo = ifTrue if predicate else ifFalse

predicate is any boolean-valued expression. For example

def abs(x):
    return x if x > 0 else -x

It is compact, economical, and easily understood. Be careful to use parens on the predicate if it is at all complex.

Upvotes: 0

John Spong
John Spong

Reputation: 1381

foo = some_value if condition else some_other_value

Upvotes: 3

Related Questions