Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the pythonic way to check that both values are None or not None together

I a have a function with 2 variables set be default to None

def foo(x, y=None, z=None):
    ...

I want to make sure that if they are passed they both need to be not None.

I did the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if y is not None:
    assert z is not None

But I wonder if there is a more elegant way of doing this check.

If only 1 of them is None I want to assert while if both of them are it’s ok.

>Solution :

You can do something like this

if (y is None) == (z is None):
   # both are None or both are not None
else:
  # one of them is None
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading