Pre/Postconditions with decorators

George Sakkis gsakkis at rutgers.edu
Fri Jan 7 05:29:30 EST 2005


"Robert Brewer" <fumanchu at amor.org> wrote:

> Ian Bicking was just talking about @require decorators:
> http://blog.ianbicking.org/already-under-our-noses.html
>
> @require(int, int)
> def gcd(a, b):
>     ...
>
> If we made a "checker" module for such things in the stdlib, we could
> write most of that:
>
> from checker import *
>
> @args((list, itemsnotNone, ))
> @returns((any, ))
> def my_sum(seq):
>     tmp=0
>     for element in seq:
>         tmp+=element
>     return tmp


I recently wrote a similar checker module; apart from regular python types and classes, it supports
'parameterized types', such as 'list of ints', 'container of floats', 'mapping with str keys and
tuples of int values', etc. Here's a demo:

# >>> from typecheck import *
# >>> @returnType(listOf(int, size=3))
# >>> @argTypes(x=str, y=containerOf(int))
# ... def f(x,y):
# ...     return [len(x)] + list(y)
# >>> f('1',[2,3])
# [1, 2, 3]
# >>> f('1',(2,3))
# [1, 2, 3]
# >>> f(1,[2,3])
# (...)
# TypeError: str expected (int given)
# >>> f('1',[2,'3'])
# (...)
# TypeError: container<int> expected ([2, '3'] given)
# >>> f('1',[2,3,4])
# (...)
# TypeError: Container of size 3 expected ([1, 2, 3, 4] given)

I can make it available somewhere (e.g. Vaults of Parnassus) if there's enough interest.

George





More information about the Python-list mailing list