Skip to content

Commit

Permalink
Abstracted decorated function argument parsing and related decorated …
Browse files Browse the repository at this point in the history
…function processing and validation into a separate function. Results are cached for speed gains on multiple calls to the same decorated function
  • Loading branch information
Pablo Acosta authored and Pablo Acosta committed Feb 25, 2015
1 parent f0795c0 commit bb1b86b
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/contracts/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,12 @@ def tmp_wrap(f):
return tmp_wrap


def contracts_decorate(function_, modify_docstring=True, **kwargs):
""" An explicit way to decorate a given function.
The decorator :py:func:`decorate` calls this function internally.
"""
_FUNCTION_CACHE = {}
def process_function(function_, **kwargs):

record = _FUNCTION_CACHE.get(function_, None)
if record:
return record

if isinstance(function_, classmethod):
msg = """
Expand Down Expand Up @@ -192,10 +194,10 @@ def f(cls, a):

returns = kwargs.pop('returns', None)

for kw in kwargs:
if not kw in all_args:
msg = 'Unknown parameter %r; I know %r.' % (kw, all_args)
raise ContractException(msg)
sdiff = set(kwargs) - set(all_args)
if sdiff:
msg = 'Unknown parameter %r; I know %r.' % (next(iter(sdiff)), all_args)
raise ContractException(msg)

accepts_dict = dict(**kwargs)

Expand Down Expand Up @@ -234,6 +236,17 @@ def f(cls, a):

is_bound_method = 'self' in all_args

_FUNCTION_CACHE[function_] = (all_args, accepts_parsed, returns_parsed, is_bound_method)

return _FUNCTION_CACHE[function_]


def contracts_decorate(function_, modify_docstring=True, **kwargs):
""" An explicit way to decorate a given function.
The decorator :py:func:`decorate` calls this function internally.
"""
all_args, accepts_parsed, returns_parsed, is_bound_method = process_function(function_, **kwargs)

def contracts_checker(unused, *args, **kwargs):
do_checks = not all_disabled()
if not do_checks:
Expand Down

0 comments on commit bb1b86b

Please sign in to comment.