Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Last active May 25, 2019 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamesbook/10e0a65907e4739284f23f81084ca174 to your computer and use it in GitHub Desktop.
Save gamesbook/10e0a65907e4739284f23f81084ca174 to your computer and use it in GitHub Desktop.
Validate kwargs in a Python function
def compare(a, b, *, key=None, **kwargs):
"""Assumption here is that you only want to handle kwargs x, y or z"""
print(a, b, key, kwargs)
if list(set(kwargs.keys()).difference(['x','y','z'])):
inv = ','.join(list(set(kwargs.keys()).difference(['x','y','z'])))
raise ValueError('Unexpected arg(s) {} in kwargs'.format(inv))
'''
>>> compare(1,2,key=4,x=2)
1 2 4 {'x': 2}
>>> compare(a=1,b=2,key=4,u=2)
1 2 4 {'u': 2}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in compare
ValueError: Unexpected arg(s) u in kwargs
>>> compare(1,2,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: compare() takes 2 positional arguments but 3 were given
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment