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

DoanVietTrungAtGmail doanviettrung at gmail.com
Mon Jan 7 01:13:53 CET 2013


*.. 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130107/c0b9e2e4/attachment-0001.html>


More information about the Tutor mailing list