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

Question:

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:

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.

Asked By: David Sriker

||

Answers:

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
Answered By: Sahil Patel

You could use the XOR operator to make sure exactly both values are what you expect, but I’m not sure that’s any more readable or elegant.

assert not ((y is not None) ^ (z is not None))

Answered By: AKX

You should avoids using an assert statement as it is intended for testing and debugging purposes, rather than controlling program flow.

def foo(x, y=None, z=None):
    if (y is None) == (z is None):
        # rest of your code here
    else:
        raise ValueError("Both y and z must be either None or not None")
Answered By: tmc

With anyall functions:

def foo(x, y=None, z=None):
    y_z = (y, z)
    if any(y_z): assert all(y_z)
Answered By: RomanPerekhrest

I think the pythonic way would be to ask for forgiveness rather than permission, aka not testing both values and dealing with the exceptions.

If this is not possible in your case then I think it depends on the logic of your function.

Is it important to fail immediatly if y and z are inconsistent ?
Do you actually just want to be sure z is not none if y isn’t (what your code currently do) ?
Is it important to inform the caller that the arguments are inconsistent ? Or you just want to avoid an error ? (ex: z has a value but not y, may be that does not provoke an error but it looks like a wrong call. If your function is "public" it seems a good practice to fail in that case. If not, you might not need to deal with it)

Answered By: Viper
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.