Decorater inside a function? Is there a way?

George Sakkis gsakkis at rutgers.edu
Sat Apr 2 13:23:53 EST 2005


It turns out it's not a "how to inflate tires with a hammer" request;
I've actually written an optional type checking module using
decorators. The implementation details are not easy to grok, but the
usage is straightforward:

from typecheck import *
@returns(listOf(int, size=3))
@expects(x=str, y=containerOf(int))
def foo(x,y):
    return [len(x)] + list(y)

>>> foo('1',[2,3])
[1, 2, 3]
>>> foo('1',(2,3))
[1, 2, 3]
>>> foo(1,[2,3])
Traceback (most recent call last):
...
TypeError: str expected (int given)
>>> foo('1',[2,'3'])
Traceback (most recent call last):
...
TypeError: container<int> expected ([2, '3'] given)
>>> foo('1',[2,3,4])
Traceback (most recent call last):
...
TypeError: container of size 3 expected ([1, 2, 3, 4] given)


George




More information about the Python-list mailing list