Last active
May 25, 2019 06:05
-
-
Save gamesbook/10e0a65907e4739284f23f81084ca174 to your computer and use it in GitHub Desktop.
Validate kwargs in a Python function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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