Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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