Type checking in python?

Cliff Crawford cjc26 at nospam.cornell.edu
Mon Jul 17 19:31:09 EDT 2000


* Paul Prescod <paul at prescod.net> menulis:
| 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 that case, it'd be more useful to check if a particular object
implements certain methods, rather than to check if it inherits from a
particular class.  For example, if you need a file-like object and you
know you will be calling its readlines() method, then you can just call

    getattr(obj, "readlines")

beforehand; if it doesn't raise an AttributeError then you're all
set.

I don't ever actually >do< that in my own code, though. ;)


| 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.


-- 
cliff crawford    -><-    http://www.people.cornell.edu/pages/cjc26/
                          Synaesthesia now!            icq 68165166



More information about the Python-list mailing list