50 points · by irahul · 15y ago · 12 comments
The lambdas are how you specify the constraints. How does operator module help here?
@ensure_args(a=lambda x: x > 10 and x < 100)
def foo(a):
pass
Here, the constraint is `a` should be greater than 10 and less than 100. Where does operator module comes in here?And the first example is using multiple lambdas to show the multiple use cases:
1. `a=lambda x: x > 10` is for the positional argument `a`.
2. `b=r'^?-\d+(\.\d+)$'` is to show if you need the arg to match a regex, you can directly pass it.
3. c=lambda x: x < 5) # `c` will be picked from `kwargs`.
And here, the comment clarifies that c isn't there in the positional args. But since arguments are looked for in both kwargs and positional args, this constraint will work.
There also are a few modules out there that implement design-by-contract's pre-/post-conditions for class instances, for example http://code.activestate.com/recipes/436834/