Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: avoiding if condition?

Which is better?

if not var:
    var = get_var()
(or)

var = var or get_var()

Also, How do I know the better of the two?
edit:
One more option from steve,

var = var if var else get_var()
like image 252
asdfg Avatar asked Mar 11 '10 06:03

asdfg


Video Answer


2 Answers

The better is the one you like better. I would use first version with if but this is very personal.

like image 130
Michał Niklas Avatar answered Sep 20 '22 18:09

Michał Niklas


When two style variations are so close stylistically, I use timeit as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:

$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of 3: 0.359 usec per loop
$ python -mtimeit -s'var=0; getvar=lambda:0' 'if not var: var = getvar()'
1000000 loops, best of 3: 0.361 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'var = var or getvar()'
10000000 loops, best of 3: 0.123 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'if not var: var = getvar()'
10000000 loops, best of 3: 0.0899 usec per loop

the if has it -- equivalent when var is false, faster when it's true.

like image 21
Alex Martelli Avatar answered Sep 18 '22 18:09

Alex Martelli