Thoughts on using isinstance

Terry Hancock hancock at anansispaceworks.com
Fri Jan 26 12:23:19 EST 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
data)

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.

Cheers,
Terry


-- 
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com




More information about the Python-list mailing list