I have the following function:
def foo(**kwargs):
if not kwargs:
# No keyword arguments? It's all right. Set defaults here...
elif ('start_index' or 'end_index') in kwargs:
# Do something here...
else:
# Catch unexpected keyword arguments
raise TypeError("%r are invalid keyword arguments" % (kwargs.keys())
Question:
I want to make sure that the only valid keyword arguments are start_index
or end_index
. Anything else will raise an error, even if mixed with the valid ones. What's the cookbook recipe to make sure that only start_index
or end_index
are accepted? Yes, I'm looking for a cookbook recipe but I'm not sure how to search for it. I'm not sure if using an if-elif-else
structure is the correct way to do it either.
Why do you need **kwargs
here? Just
def foo(start_index=None, end_index=None):
and Python will perform all validation for you.
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