Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 378
tamakisquare Avatar asked Mar 11 '26 17:03

tamakisquare


2 Answers

identifier = None if obj is None else obj.id
like image 74
Tom Zych Avatar answered Mar 13 '26 15:03

Tom Zych


identifier = getattr(obj, "id", None)
like image 24
Andrew Clark Avatar answered Mar 13 '26 15:03

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!