Skip to content

Instantly share code, notes, and snippets.

@Ahuge
Created December 6, 2016 22:06
Show Gist options
  • Save Ahuge/0d67ac93fc67f717b612e8391797589d to your computer and use it in GitHub Desktop.
Save Ahuge/0d67ac93fc67f717b612e8391797589d to your computer and use it in GitHub Desktop.
Default Value decorator.This allows you to optionally pass a "default" value into your function and have it returned in the case of a falsey value returned.
def keep_signature(input_function):
def to(function):
f_name = input_function.func_code.co_name
args = input_function.func_code.co_varnames[:input_function.func_code.co_argcount]
kw_list = input_function.func_defaults or []
kwargs = args[-len(kw_list):] if len(kw_list) else [] # because kwargs are last
args = args[:len(kw_list)] if len(kw_list) else args
d_kwargs = {}
for k, v in zip(kwargs, kw_list):
d_kwargs[k] = v
kw_str = ", ".join(["%s=%s" % (x, d_kwargs[x]) for x in d_kwargs])
doc_str = "This is a wrapper for the following method:\n\n{name}({args}{kwargs}){doc}".format(
name=f_name,
args=", ".join(args),
kwargs=", " + kw_str if kw_str else "",
doc=input_function.__doc__ or "")
function.__doc__ = doc_str
return function
return to
def default_value(inFunction):
@keep_signature(inFunction)
def inner(*args, **kwargs):
_all_names = inFunction.func_code.co_varnames[0:inFunction.func_code.co_argcount]
args = list(args)
new_kwargs = {}
for name in _all_names:
if args:
new_kwargs[name] = args.pop()
else:
break
for kwarg in kwargs:
new_kwargs[kwarg] = kwargs[kwarg]
default = None
if "default" in new_kwargs:
default = new_kwargs.pop("default")
r = inFunction(**new_kwargs)
return r or default
return inner
@default_value
def my_func(int_value):
"""
feeep test docstring copying. test test
"""
if int_value % 3:
return None
if int_value *2 > 33:
return None
return int_value * 5
help(my_func)
print(
my_func(4, default=42)
)
print(
my_func(4)
)
@Ahuge
Copy link
Author

Ahuge commented Dec 6, 2016

Results from executing

Help on function inner in module __main__:

inner(*args, **kwargs)
    This is a wrapper for the following method:
    
    my_func(int_value)
        feeep test docstring copying. test test

42
None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment