Is this a good idea or a waste of time?

hiaips rosedb0 at gmail.com
Thu Aug 24 22:02:06 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 (in addition to seeing if they meet other kinds of precondition
> constraints)?  Like:
>
>     def foo(a, b, c, d):
>        assert type(a) == str
>        assert type(b) == str
>        assert type(c) == int
>        assert type(d) == bool
>        # rest of function follows
>
> 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"?
>
> -- Arcadio

Many developers who move from a statically-typed languages to dynamic
ones go through this same sort of thought process. I was no different
in that regard, but as I've done more and more Python, I've found that
I just don't encounter type issues all that often. Above all, I see
duck typing as a net benefit - its inherent flexibility far outweighs
the lack of "compile-time" type safety, in my mind.

Along these lines, I'll point you to this article by Bruce Eckel called
"Strong Typing vs. Strong Testing":
http://www.mindview.net/WebLog/log-0025. The bottom line: Focus on unit
tests rather than explicit type checks when you want to verify the
runtime safety of your code. You'll find many more errors this way.

Hope this helps...
--dave




More information about the Python-list mailing list