Reputation: 17077
Say, I have the following Python code
if obj is None:
identifier = None
else:
identifier = obj.id
where obj
is a Python object whose class definition is not included
I barely remember there's a more concise syntax (like a one-line code?) that can achieve the same. If I wasn't dreaming, can someone please advise what that simpler syntax might be? Thanks.
Upvotes: 3
Views: 739
Reputation: 7419
If you use an old python version without conditional expressions, you can resort on the evaluation semantics of boolean expressions: The value of a boolean expression is the value of that term in the expression which determines its final value. That sounds quite abstract, but in your case you can say:
((obj is None and [None]) or [obj.id])[0]
If obj
is None
you have
((True and [None]) or [obj.id])[0]
which is
([None] or [obj.id])[0]
As [None]
represents a True
value, which can be or
ed with any expression without changing the value of the or
expression the result is [None][0]
which is None
If obj
is not None
you have
((False and [None]) or [obj.id])[0]
which is
(False or [obj.id])[0]
= ([obj.id])[0]
= obj.id
This is how you had to simulate the ternary operator aka "conditional if expression" if former times.
The general pattern is a if b else c
is the same as
(b and [a] or [c])[0]
Upvotes: 1