Search code examples
pythonnullin-place

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)


Solution

  • You can't do what you want because there isn't an inplace logical or, but I don't think you really want to anyway. In Python "readability counts", and a or= b or whatever is definitely very difficult to read. a = a or 5 is quite a common idiom, and so isn't too unreadable, but or= I think definitely would be. For this reason, I think it is worth doing if a is not None instead. In answer to your question about possible dangers of a = a or default, the only one I can think of is if default has a Boolean value of False then it breaks.