Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying null checks with inplace OR

I am simplifying some null/false checks in python in the following form:

This:

if not a:
    a = 'foo'

Can be simplified to this:

a = a or 'foo'

And, looking above is natural to try to simplify even further, like this:

a |= 'foo'

But, the python's in-place or is actually doing in-place bitwise or:

a = None
a |= 'foo'
=> TypeError: unsupported operand type(s) for |=: 'NoneType' and 'str'

a = 'foo'
a |= 'bar'
=> TypeError: unsupported operand type(s) for |=: 'str' and 'str'

a = 1
a |= 2
print a
=> 3

a = 2
a |= 3
print a
=> 3

So, the questions are: Does Python has an inplace or? Also, do you see problems doing a simplified null/false check like this?

Disclaimer

I am aware that a is not None is not the same as not a. The former evaluates if a is indeed not a None value while the latter evaluates if a is not something that evaluates to False (like False, None, 0, '' (empty string), [], {} (empty collections) and so on)

like image 805
Bruno Penteado Avatar asked Feb 14 '23 15:02

Bruno Penteado


1 Answers

Python does not have an in-place logical or, only the bitwise version you are already using.

like image 189
jonrsharpe Avatar answered Feb 23 '23 10:02

jonrsharpe