How to check in python that at least one of the default parameters of a specified function

What is the best practice in python to check if at least one of the default parameters is specified for a function?

Suppose we have some function:

def some_function(arg_a=None, arg_b=None, arg_c=False)

with some default options. In my case, I need to check if the parameter is specified arg_aor arg_b. So I decided to implement something like this:

def some_function(arg_a=None, arg_b=None, arg_c=False):
    ...
    if arg_a is not None:
        ...
    elif arg_b is not None:
        ...
    else:
        raise ValueError('Expected either arg_a or arg_b args')
    ...
    ...

So, what is an even more pythonic way to implement such functionality?

+4
source share
4 answers

You can use allto check if they are all equal Noneand raise ValueError:

if all(v is None for v in {arg_a, arg_b}):
    raise ValueError('Expected either arg_a or arg_b args')

if-elif :

f(arg_a=0) # ok    
f(arg_b=0) # ok
f()        # Value Error  

, 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')

.

, , .

+4

, arg_a arg_b, .

if not arg_a and not arg_b:
    raise ValueError(...)

, arg_a arg_b , // .. .

, None "falsies", False, 0, "", [], {},() ..:

if arg_a is None and arg_b is None:
    raise ValueError(...)
+3

kwargs, :

def some_function(**kwargs):
    reqd = ['arg_a', 'arg_b']
    if not all(i in kwargs for i in reqd):
        raise ValueError('Expected either {} args'.format(' or '.join(reqd)))

    arg_a = kwargs.get('args_a')
    arg_b = kwargs.get('args_b')
    arg_c = kwargs.get('args_c', False)
+1

, ,

The solution uses a function locals, dict.valuesand any:

def some_function(arg_a=None, arg_b=None, arg_c=False):
    args = locals()
    if (any(args.values()) == True):
        print('Ok')
    else:
        raise ValueError('At least one default param should be passed!')

some_function(False, 1)            # Ok
some_function('text', False, None) # Ok
some_function(0, False, None)      # Error

https://docs.python.org/2/library/functions.html#any

0
source

Source: https://habr.com/ru/post/1650836/


All Articles