Last active
October 27, 2021 13:36
-
-
Save root-11/95e0bb97140dff11ceeadd9d31c592d7 to your computer and use it in GitHub Desktop.
Decorator for filtering keywords from a big dict.
This file contains hidden or 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
import functools | |
import inspect | |
def kwarg_filter(): | |
def decorator(fn): | |
keys = inspect.getfullargspec(fn).args # <-- This reads the signature of the function. | |
@functools.wraps(fn) | |
def inner(*args, **kwargs): | |
new_kwargs = {k:kwargs[k] for k in keys} # <-- This filters out unnecessary keywords. | |
return fn(*args, **new_kwargs) | |
return inner | |
return decorator | |
@kwarg_filter() | |
def func(a, b, c, d, e, f): | |
print(a, b, c, d, e, f) | |
@kwarg_filter() | |
def func2(a,c,f): | |
print(a,c,f) | |
@kwarg_filter() | |
def func3(what, f): | |
print(what, f) | |
big_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50, 'f': 60, "What": False, 'ohno': True} | |
# We can now call `func` with excess keywords and it will filter the excess kwargs out. | |
func(**big_dict) | |
func2(**big_dict) | |
func3(**big_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment