Type checking in python?

paul at prescod.net.bbs paul at prescod.net.bbs
Mon Jul 17 01:20:02 EDT 2000


Matthew Cline wrote:
>
>   def my_func(foo, bar, quux):
>      if not isinstance(quux, Quux):
>         raise RuntimeError("param 'quux' must be of class 'Quux'")

Let me also point out that in many cases, this style of programming
would be frowned upon by serious Python programmers. For instance, if
you check that something is a string, your code will complain when it is
handed a Unicode string, even though it would probably work fine. If you
check that it is an open file, then your code probably will complain
about stringIO file-like objects, even though it would probably work
fine. If you check that it is an integer, your code will complain about
integers, even though ti would probably work fine.

In general, the Python philosophy is to "just try it" and see if it
works. Sometimes type checks are appropriate but if you do it on the
entry to every function, you are probably doing too much work and making
your own life (or someone else's) harder later on.
--
 Paul Prescod - Not encumbered by corporate consensus
It's difficult to extract sense from strings, but they're the only
communication coin we can count on.
	- http://www.cs.yale.edu/~perlis-alan/quotes.html



More information about the Python-list mailing list