Python’s equivalent to null-conditional operator introduced in C# 6

How about:

s = sb and sb.ToString()

The short circuited Boolean stops if sb is Falsy, else returns the next expression.

Btw, if getting None is important…

sb = ""

#we wont proceed to sb.toString, but the OR will return None here...
s = (sb or None) and sb.toString()

print s, type(s)

output:

None <type 'NoneType'>

There was some over-eager deletion of comments in the past, which I want to replicate here as a caveat:

commenter : Do you really think it is a good idea to do this in Python, a language that prides itself on code readability?

me : No, I don’t. This answers the question – and illustrates some aspects of boolean short-circuiting – but is too “clever” by half. If you have a reason to use this form, do so, but be aware its intent is not crystal clear at first glance.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)