-
-
Save mahenzon/a6c2804a2d18a2ab75630bb5d93693c8 to your computer and use it in GitHub Desktop.
Pass safe kwargs to classes / functions
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
import inspect | |
import functools | |
def check_spec(func: callable, kwargs: dict): | |
spec = inspect.getfullargspec(func) | |
if spec.varkw: | |
return kwargs | |
return {k: v for k, v in kwargs.items() if k in spec.args} | |
def safe_kwargs(func_or_class): | |
@functools.wraps(func_or_class) | |
def wrap(*args, **kwargs): | |
spec = check_spec(func_or_class, kwargs) | |
return func_or_class(*args, **spec) | |
return wrap | |
@safe_kwargs | |
class Foo: | |
def __init__(self, foo, bar=None): | |
print(foo, bar) | |
Foo(42, bar='ok', baz='ignored') | |
# P.S. If you're 100% sure that a class won't have a `**kwargs` in initializer, use this solution: | |
# It doesn't request spec for each init so it's faster in about 5 times | |
def safe_kwargs(func_or_class): | |
spec = inspect.getfullargspec(func_or_class) | |
all_args = spec.args | |
@functools.wraps(func_or_class) | |
def wrap(*args, **kwargs): | |
accepted_kwargs = {k: v for k, v in kwargs.items() if k in all_args} | |
return func_or_class(*args, **accepted_kwargs) | |
return wrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment