tamakisquare
tamakisquare

Reputation: 17077

Python: A more concise syntax for variable assignment when accessing a NoneType object

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

Answers (3)

rocksportrocker
rocksportrocker

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 ored 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

Andrew Clark
Andrew Clark

Reputation: 208615

identifier = getattr(obj, "id", None)

Upvotes: 2

Tom Zych
Tom Zych

Reputation: 13586

identifier = None if obj is None else obj.id

Upvotes: 8

Related Questions