Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python checking if exactly one object is not None [closed]

Tags:

python

I have two python objects a and b.

What is the best/most-efficient/most-pythonic way to check if exactly one of these objects is None?

like image 680
Saqib Ali Avatar asked Oct 18 '25 04:10

Saqib Ali


2 Answers

Use Python's ^ (XOR) operator.

(a is None) ^ (b is None)
like image 84
Bill the Lizard Avatar answered Oct 19 '25 18:10

Bill the Lizard


What you effectively want is the XOR or Exclusive OR function on whether those two objects are None. The following should work for you:

(a is None) ^ (b is None)

A more exhaustive answer on how to get XOR on objects in Python can be found here:

How do you get the logical xor of two variables in Python?

like image 35
pcurry Avatar answered Oct 19 '25 19:10

pcurry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!