How to check in python that at least one of the default parameters of the function specified
You could use all
to check if they all equal None
and raise the ValueError
:
if all(v is None for v in {arg_a, arg_b}):
raise ValueError('Expected either arg_a or arg_b args')
this gets rid of those if-elif
clauses and groups all checks in the same place:
f(arg_a=0) # ok
f(arg_b=0) # ok
f() # Value Error
Alternatively, with any()
:
if not any(v is not None for v in {arg_a, arg_b}):
raise ValueError('Expected either arg_a or arg_b args')
but this is definitely more obfuscated.
In the end, it really depends on what the interpretation of pythonic actually is.
Depends on what you expect as values for arg_a
and arg_b
, but this is generally sufficient.
if not arg_a and not arg_b:
raise ValueError(...)
Assumes that arg_a
and arg_b
are not both booleans and cannot have zeros, empty strings/lists/tuples, etc. as parameters.
Depending on your needs, you can be more precise if you need to distinguish between None and 'falsies' such as False, 0, "", [], {}, (), etc.:
if arg_a is None and arg_b is None:
raise ValueError(...)