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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With