Skip to content

Instantly share code, notes, and snippets.

@dcolish
Created November 18, 2011 05:57
Show Gist options
  • Select an option

  • Save dcolish/1375728 to your computer and use it in GitHub Desktop.

Select an option

Save dcolish/1375728 to your computer and use it in GitHub Desktop.
Contract style params for python
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