Type checking in python?
Eric Hopper
hopper at omnifarious.mn.org
Tue Jul 18 11:29:31 EDT 2000
In article <397296BC.415C97E1 at prescod.net>, Paul Prescod
<paul at prescod.net> wrote:
> 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.
Oh, yes. Inheritance by mysteriously coiniciding method names. How fun.
Actually, I'm going to write a type checking function that throws a
coherent exception when the type of the argument fails to be a particular
type. I'll probably put in some specialized checks for the built in types
so it'll accept things that are objects of those types, or derived from
the User<class> version. It'd be nice if Python had lisp-like macros, but
they aren't necessary.
My problem is this:
Just accepting any old type, and letting it error out when it tries to
access a non-existent attribute is very confusing for people trying to use
your code. Heck, maybe you store away their object, and then call the
offending method at some random later point. I bet it'd be a heck of a
lot of fun to try to trace down why the exception happened then.
Type checking and the scoping rules are the only two problems I have with
Python so far. Other than that, it's a wondefrul language.
--
Eric Hopper (hopper at omnifarious.mn.org, http://www.omnifarious.org/~hopper)
More information about the Python-list
mailing list