Created
November 18, 2011 05:57
-
-
Save dcolish/1375728 to your computer and use it in GitHub Desktop.
Contract style params for python
This file contains hidden or 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 wraps | |
| from inspect import getcallargs | |
| def assert_params(*contracts): | |
| _contracts = [] | |
| for contract in contracts: | |
| _contracts.append((contract, compile(contract, '', 'eval'))) | |
| def decorator(fn): | |
| @wraps(fn) | |
| def new_fn(*args, **kw): | |
| callargs = getcallargs(fn, *args, **kw) | |
| for contract in _contracts: | |
| res = eval(contract[1], callargs) | |
| assert res, "Contract assertion failed: %s" % contract[0] | |
| return fn(*args, **kw) | |
| return new_fn | |
| return decorator | |
| @assert_params('mork > 10', 'isinstance(baz, str)') | |
| def foo(mork, baz=''): | |
| print mork | |
| foo(11, '') | |
| try: | |
| foo(1, '') # Fails | |
| except Exception as e: | |
| print e | |
| try: | |
| foo(11, 1) # Fails | |
| except Exception as e: | |
| print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment