Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Let's suppose we have some function:

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

with some default parameters. In my case, I need to check if either arg_a or arg_b is specified. So I thought of implementing 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 more pythonic way to implement such kind of functionality?

like image 308
machin Avatar asked Aug 10 '16 19:08

machin


People also ask

How do you check parameters in Python?

Practical Data Science using Python To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions a Method and foo.

What is the default parameter for the method in Python?

In Python, a default parameter is defined with a fallback value as a default argument. Such parameters are optional during a function call. If no argument is provided, the default value is used, and if an argument is provided, it will overwrite the default value.

Does Python allow default values for parameters?

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.

Does a function have to have at least one argument in Python?

You can define a function that doesn't take any arguments, but the parentheses are still required. Both a function definition and a function call must always include parentheses, even if they're empty. Here's how this code works: Line 1 uses the def keyword to indicate that a function is being defined.


1 Answers

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.

like image 156
Dimitris Fasarakis Hilliard Avatar answered Sep 22 '22 18:09

Dimitris Fasarakis Hilliard