3 ms·
Your note is very important, I think it would be good to give it more emphasis. What works flawlessly, however, is: In [1]: a = None In [2]: b = 0 In [3
by shiftingleft 6y ago
Your note is very important, I think it would be good to give it more emphasis.
What works flawlessly, however, is:
In [1]: a = None
In [2]: b = 0
In [3]: (a is None) ^ (b is None)
Out[3]: True
Alternatively, as suggested in another comment, you can use inequality as a replacement for XOR:
In [4]: (a is None) != (b is None)
Out[4]: True
Another error prone pattern is the following:
In [5]: a or b
Out[5]: 0
Which can behave differently depending on the order of elements/values:
In [6]: b or a
Out[6]: None # should be 0
Since b is zero, it doesn't count.
Less error prone, but also more verbose is:
In [10]: a if a is not None else b
Out[10]: 0
- sleavey 6y agoLesson for myself: check my working. The test I actually used the XOR in, that I was referring to, uses the first example you wrote - I agree, this is much better. However, I also like your second example, which is arguably clearer. Thanks!