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.
For the sake of completeness, Here’s an alternative that still uses
**kwargs.But, you shouldn’t want to use this when you don’t absolutely need it, use regular parameters with default values (as in Roman Bodnarchuk’s answer).
Cases when you might need this is when you also want to use
*args, and need a way to distinguish the keyword arguments from arbitrarily man positional arguments. using**kwargsthis way forces the keyword arguments to be passed as keywords; A positional argument can never find its way into**kwargs.Another reason is so that you can really distinguish between a default and an explicit parameter which happens to be the default.
Noneis often used as a default value for arguments to indicate “the argument doesn’t apply”, but sometimes you actually need to interpret theNoneas something other than a default. Checking for the presence or absence of a key in the**kwargsdict can accurately distinguish between these cases. (An alternative is to create an instance of a subclass ofobjectwhos sole purpose is to be the default value of a specific argument to that specific function)