Created
August 9, 2013 19:08
-
-
Save tadeck/6196271 to your computer and use it in GitHub Desktop.
Decorator allowing function to receive information on the parameters that were passed to it during call, regardless of whether they were positional or keyword-based.
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
from functools import partial, wraps | |
def explicit_checker(func=None, names_arg='explicit_params'): | |
"""Decorator of function, allowing the function to receive names of attributes | |
that were explicitly set (either positionally or as keyword arguments). The | |
explicitly set arguments are received as set assigned to some keyword argument | |
at function call (default name is "explicit_params"). | |
Example usage: | |
>>> @explicit_checker | |
def test(a=1, b=2, explicit_params=None): | |
return a, b, explicit_params | |
>>> test(1) | |
(1, 2, set(['a'])) | |
>>> test(b=3) | |
(1, 3, set(['b'])) | |
>>> @explicit_checker | |
def test(a=1, explicit_params=None, *args, **kwargs): | |
return a, args, kwargs, explicit_params | |
>>> test(a=2, b=3) | |
(2, (3,), {'b': 3}, set(['a', 'b'])) | |
:param func: function to be decorated | |
:param names_arg: name of the argument to store set of names | |
:return: decorated function | |
""" | |
if func is None: | |
# Decorator called not on function, return another decorator | |
return partial(explicit_checker, names_arg=names_arg) | |
varnames = func.func_code.co_varnames | |
@wraps(func) | |
def _wrapper(*args, **kwargs): | |
kwargs[names_arg] = set(list(varnames[:len(args)]) + kwargs.keys()) | |
return func(*args, **kwargs) | |
return _wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment