Decorater inside a function? Is there a way?

Ron_Adam radam2 at tampabay.rr.com
Sat Apr 2 21:57:08 EST 2005


On 2 Apr 2005 10:23:53 -0800, "George Sakkis" <gsakkis at rutgers.edu>
wrote:

>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)
>

Hi George,

I wrote one like that too yesterday once I figured out how to pass the
arguments, except not with 'conainerof' emplemented. That's a nice
touch.

>>@define((int, int, float), (int, list))
>>def somefunction( a_int, b_int, c_float):
	# some stuff
	return an_int, an_list

It checks both the inputs and returns for types and number of items.
And gives error appropriate for both. 

Next, would be to surround the 'def define' statements with an
"if __debug__: " statement so it can be turned off for the final
version.  I wonder if a decorator, that just passes values straight
though, gets optimized out or not?  Or if there's another way to turn
of a decorator?

I also have a test_type function that can be put inline that tries to
adapt the value before it gives an error.

These are interesting problems to solve and go into my tool box,
although I don't have a need for them at the moment. :)

Cheers,
Ron




More information about the Python-list mailing list