Purpose of Python Type Checking?

Erik Max Francis max at alcyone.com
Sun Jan 26 23:15:50 EST 2003


Mongryong wrote:

> Why do people use type checking in Python?
> 
> Yes, I know its to "ensure" that parameters are valid but doesn't that
> defeat the whole purpose of one of Python's main feature? Polymorphism
> and code reuse.  Who cares if a parameter is not of type(X), as long
> as
> it has the methods and member variables necessary.  If the parameter
> is
> missing stuff, then an exception is thrown.
> 
> The reason I'm asking is because I don't use type checking at all but
> I
> ses a lot of other code use it.  So, is there a good reason I should
> be
> using it too?

In general I agree with you.  I can think of two cases where I use type
checking, at least temporarily:

One is where you have an API and you want some sort of polymorphism. 
For instance, EmPy has an include API that takes either 1. a filename (a
sring) or 2. a file-like object.  It does (from memory):

	if type(fileOrFilename) is types.StringType:
	    # it's a string, so open a file
	    file = open(fileOrFilename, 'r')
	else:
	    # it's a file-like object, so just treat it like one
	    file = fileOrFilename

[A design requirement of EmPy is that is 1.5.2 compatible, so no
"type(...) is str" or "use file, not open" comments, please.]  In other
words, maybe for some special (invariably builtin) types, I'll do
something special, but otherwise I'll just assume the passed-in object
has the proper interface.

The other is debugging.  If I'm building complex data structures and I
want to make sure that _I_, as the implementor of the system, don't make
some mistakes, I'll often put an

	assert isinstance(argument, SomeSpecificClass)

simply because I know that for the development cycle the only type that
should be passed in there is one I've created, and so if, during
development, anything else ends up there I've made a mistake and I want
to catch it right away.  (Such asserts would then be removed before the
API is frozen and the code is released.)

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ This moment is mine / So I'm taking my time
\__/ Chante Moore
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.




More information about the Python-list mailing list