Is it possible to write a PEP 8 compliant, one-line, conditional expression that can do nothing?
Let's say I have the following code
if condition_met:
do_something()
Where I call do_something
for a specific condition, but otherwise do nothing. I could condense it to one line with the following
if condition_met: do_something()
But that wouldn't be PEP 8 compliant. I was hoping something like the following would work.
do_something() if condition_met
But its a syntax error unfortunately. I tried the next, fairly silly, one-liner, but it too is a syntax error even though it's multi-line equivalent is valid.
do_something() if condition_met else pass # syntax error
...
if condition_met:
do_something()
else:
pass # valid syntax
I've came up with the following one line expression that is PEP-8 compliant, or at least makes flake8
happy.
do_something() if condition_met else None
But the above isn't very pythonic and the multi-line equivalent makes even less sense than the one using pass
. Is there a way to do nothing in a one-line expression while still being PEP 8 compliant?
You could do:
condition_met and do_something()
The short-circuiting behavior of and
means do_something()
is only invoked if condition_met
is truthy (the result of the expression would be whatever do_something()
returned in that case).
I'd personally recommend sticking to the two-liner, or even violating PEP8 and putting the two-liner on one line if you really hate two-lining it. Using and
for flow control without the result of the whole expression being used is more ugly/confusing than the straightforward solution.