[Python-ideas] ternary without else

Jacco van Dorp j.van.dorp at deonet.nl
Fri May 25 06:06:42 EDT 2018

I would like to carefully suggest a half form of the ternary expression.

Currently, you can write code like:

>>> if cond:
>>>    do_something

However, especially if the condition and action are both really
simple, taking two lines feels like a bit of a waste. So I sometimes

>>> if cond: do_something

However, this isn't PEP8 compliant, and every linter complains about
it. They'd be right if the condition and action were a bit more

I would very much like to write:

>>> do_something if cond

and be done with it. Like a ternary expression but without the else clause.

I know this is probably not gonna make it due to "not strong enough
pro's, just swallow the linters complaints and roll with the 'if cond:
do_something' if you care so much about that 1 line", but I still
wanted to make my case.

===Example Usecases===
(inside loop)
>>> continue if x > 50

>>> logger.info(f"{var}") if DEBUG
(Logging module ofc already does this, and in a much better way.
However, if var is expensive to get it could save a bit of time.)

(singleton creation)
>>> cls.inst = super().__new__(cls, *args, **kwargs) if cls.inst is None

>>> cache.warm() if cache is None

More information about the Python-ideas mailing list