[Python-ideas] ternary without else
Steven D'Aprano
steve at pearwood.info
Fri May 25 07:38:24 EDT 2018
On Fri, May 25, 2018 at 12:06:42PM +0200, Jacco van Dorp wrote:
> I would like to carefully suggest a half form of the ternary expression.
[...]
> However, this isn't PEP8 compliant
PEP 8 is not holy writ. Ignore it when your code is better for ignoring
it.
> 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 believe there are a number of languages out there which have clauses
like this. I'm not going to do a language survey, but two popular
choices are:
something if condition
something unless condition
and similar variations. For example, Ruby:
http://www.railstips.org/blog/archives/2008/12/01/unless-the-abused-ruby-conditional/
> ===Example Usecases===
> (inside loop)
> >>> continue if x > 50
That's not going to work if this is an *expression*. You can't say:
continue if x > 50 else "don't continue"
The problem with an expression is, what does this return if the clause
is false? So the comparison to the ternary if expression is invalid.
This would have to be a statement.
>
> (logging)
> >>> 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.)
If the logging module already solves this problem in "a much better
way", why are you including a much worse way?
> (singleton creation)
> >>> cls.inst = super().__new__(cls, *args, **kwargs) if cls.inst is None
And this is a problem: that is ambiguous with the if...else ternary
expression. Presumably you want that to look like a statement:
cls.inst = super().__new__(cls, *args, **kwargs)
guarded by an if statement:
if cls.inst is None
but it can also be interpreted as an assignment:
cls.inst =
with an incomplete ternary expression:
super().__new__(cls, *args, **kwargs) if cls.inst is None
else what????
Even if we decide to make it a rule that one interpretation beats the
other, we still have to expect people will be confused by it. So we
ought to be cautious about syntax which is ambiguous in this way.
> (cache)
> >>> cache.warm() if cache is None
There are about a zillion things that you can write like this:
if condition:
do something
so the use-cases certainly exist. The only question is a matter of taste
and familiarity, whether it nicer to write it as above or like:
do something if condition
--
Steve
More information about the Python-ideas
mailing list