Simplify null checks with inplace OR

I simplify some null / false checks in python as follows:

It:

if not a:
    a = 'foo'

The following can be simplified:

a = a or 'foo'

And, looking above, it is natural to try to simplify even more, for example:

a |= 'foo'

But, python in-place oractually performs locally differently 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 have an inplace or? Also, do you see problems with a simplified null / false check like this?

Renouncement

I know that a is not Nonedoes not match not a. The first evaluates whether a truly is not a valid value None, and the latter judges whether a value is not something that is estimated as False(e.g., False, None, 0, ''(blank) [], {}(empty collection), etc.)

+4
3

, , or, , . "" Python a or= b -, . a = a or 5 - , , or= . , , if a is not None. a = a or default, , default False, .

+2

Python or , , .

+3

, .

As for a = a or 'foo', I saw it and used it often. As far as I know, this is a common idiom. It is explicit, and the behavior is pretty obvious, so I don't know any PEP guidelines that it breaks. I actually consider it more readable than a |= 'foosince it does not resort to rare type operators and reads naturally.

+3
source

All Articles