Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an invalid keyword argument

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.

like image 644
Kit Avatar asked Dec 02 '22 01:12

Kit


1 Answers

Why do you need **kwargs here? Just

def foo(start_index=None, end_index=None):

and Python will perform all validation for you.

like image 146
Roman Bodnarchuk Avatar answered Dec 07 '22 22:12

Roman Bodnarchuk