[Tutor] Decorators: Are they good for checking inputs and outputs?

Dave Angel d at davea.name
Mon Jan 7 01:43:09 CET 2013


On 01/06/2013 07:13 PM, DoanVietTrungAtGmail wrote:
> *.. Could you perhaps give a concrete example of a situation where
> a decorator would be useful for checking the inputs to a function? .. Oscar*
>
> Say I write a function that expects 5 positional arguments, and up to 4 **
> arguments. Now I want to:
> a- check that the first positional argument is a sorted list. If not a
> list, raise an error. If an unsorted list, sort it and pass to the function
> b- check that the 5th position argument is an 0 < int < 10
> c- check that no more than 4 ** arguments are passed
>
> In the decorators-make-my-life-simple scenario I hope for, I'll simply open
> my box of decorators, pick 3 relevant decorators, and put the 3 @ lines
> above my function. In the @ for the b- test, I'll pass a 5 to tell the
> decorator to look at the 5th argument, and similarly a 4 for the decorator
> checking c-.
>
> Then I write another function, whose test requirements will be different,
> I'll simply pick decorators relevant to it, then go on writing more code.
>
> If this scenario works as expected, I can focus my mind on the concepts I'm
> working on rather than having to interrupt the flow of thoughts to write
> test code.
>
> *.. See the recent discussion on Test Driven Development .. Alan*
>
> Yes I followed the recent discussion about unit testing. I suppose that
> decorators can't do everything that a comprehensive unit testing can, but
> probably decorators plus a few doctests would suffice for my purpose.
>
> Trung
>
>

I'd say you don't understand TDD at all.  Your decorators are NOT
validating the function they're applied to, and in one case, they
totally modify its behavior.

Your decorators make no effort to ensure anything about the behavior of
the function, they just test whether the caller is obeying some rules. 
And even there, nothing here will test what happens if some future
caller uses different arguments.

Part of the requirement for test code is that its presence have no
effect on customer-running code.  In some environments, that's done by
doing conditional compiles. But if you disabled all these decorators,
suddenly the function will get unsorted data.

Sounds like you're trying to emulate the type system of C++, or even
Pascal or Ada.  Why not just use such a language then?  If you really
want to constrain the caller by code you write at the function site,
then use a compiler that can actually reliably make the checks you're
talking about, and make most of the checks at compile time.

Python is useful for duck-typing, and that's the first feature you're
trying to test out of.

-- 

DaveA



More information about the Tutor mailing list