Created
July 27, 2022 19:34
-
-
Save lucaswiman/995f18763d088555547a74864254ac0b to your computer and use it in GitHub Desktop.
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, functools | |
>>> | |
>>> class Void: | |
... pass | |
... | |
>>> def handle_defaults(f, undefined=Void): | |
... sig = inspect.signature(f) | |
... @functools.wraps(f) | |
... def defaults_handled(*args, **kwargs): | |
... bound = sig.bind(*args, **kwargs) | |
... bound.apply_defaults() | |
... for name, value in list(bound.arguments.items()): | |
... if value is undefined: | |
... field = sig.parameters[name] | |
... if field.default is not inspect._empty: | |
... bound.arguments[name] = field.default | |
... return f(*bound.args, **bound.kwargs) | |
... return defaults_handled | |
... | |
>>> | |
>>> @handle_defaults | |
... def func(val="default"): | |
... return val | |
... | |
>>> func(Void) | |
'default' | |
>>> | |
>>> def wrapper(val=Void): | |
... return func(val) | |
... | |
>>> | |
>>> wrapper() | |
'default' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment