Is this a good idea or a waste of time?

Terry Hancock hancock at anansispaceworks.com
Mon Aug 28 20:24:05 EDT 2006


asincero wrote:
>  Would it be considered good form to begin every method or function
>  with a bunch of asserts checking to see if the parameters are of the
>  correct type [...]
>
>  This is something I miss from working with more stricter languages
>  like C++, where the compiler will tell you if a parameter is the
>  wrong type. If anything, I think it goes a long way towards the code
>  being more self documenting. Or is this a waste of time and not
>  really "the Python way"?

Definitely "unpythonic".

It's generally better to ask if an object "acts right" rather than if
it "is right".  In other words, if you're going to add two objects,
it's more important that they support addition than that they
are integers, longs, floats, or matrices.  This makes your code
more portable, because people might create new numeric types
(say "measurements" or "rationals"). If you leave things open,
then the author of such modules can use your code (they may
have to test special cases if their objects don't behave the same
way as you expect them to, but that becomes their problem).
On the other hand, if your code just arbitrarily breaks because
the objects fail a typecheck, that's an unnecessary obstacle.

If you need assertions, it's better to ask more specifically what will
break the code (e.g. objects that don't support addition -- which
you can check by doing an addition or by looking for th __add__
method. But then, if you need addition support, then your code
probably already has an addition, so why not just let it fail there?).

So be more minimal and throw in checks for specific problems --
especially the ones that would cause a wrong result rather than
an exception.

Cheers,
Terry


-- 
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com




More information about the Python-list mailing list