Thoughts on using isinstance

Terry Hancock hancock at
Fri Jan 26 18:23:19 CET 2007

Bruno Desthuilliers wrote:
> abcd a écrit :
>>Well my example function was simply taking a string and printing, but
>>most of my cases would be expecting a list, dictionary or some other
>>custom object.  Still propose not to validate the type of data being
>>passed in?
> Yes - unless you have a *very* compelling reason to do otherwise.

Some compelling reasons:

1) Some action of the function is irreversible (for example, deletion of

2) The function will get many wrong parameters in normal use, and the
function's action is expensive (disk accesses, re-writing flash memory,
fetching things from remote servers, whatever)

3) The inputs are from a web form or other insecure source, and you
want to reduce the number of unexpected cases you have to deal with.
(proof against error is not the same as proof against deliberate malice)

4) The function DOESN'T fail with a certain wrong parameter, but instead
does something it shouldn't. Catch the failing case and deal with it, or
if there are many, insist on the successful case.

Even when you do have to validate, it usually promotes flexibility of
the code to check for functionality (e.g. presence of necessary methods)
rather than specific inheritence.

Using "isinstance" is one of those practices that can really help in
quick testbed code or in a prototype, but you usually want to take it
out later.


Terry Hancock (hancock at
Anansi Spaceworks

More information about the Python-list mailing list