Thoughts on using isinstance

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Wed Jan 24 19:24:05 CET 2007


abcd <codecraig at gmail.com> wrote:
> 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?


There are many people here who will indeed suggest that you're still
best off not validating.

There are various points to consider:

 - Not adding the validation code saves a certain amount of effort.

 - Not adding the validation code avoids one source of possible bugs.

 - Not adding the validation code can make your code more readable, in
   that there's that much less uninteresting code for your readers to
   skip before they get to the meat.

 - Adding the validation code can make your code more readable, in that
   it can be clearer to the readers what kind of values are being
   handled.

 - If you validate, you can raise an exception from the start of your
   function with a fairly explicit message. If you don't validate,
   you're likely to end up with an exception whose message is something
   like 'iteration over non-sequence', and it might be raised from some
   function nested several levels deeper in.

   The latter can be harder for the user of your function to debug (in
   particular, it may not be easy to see that the problem was an invalid
   parameter to your function rather than a bug in your function itself,
   or corrupt data elsewhere in the system).

 - If you don't validate, your function will accept anything that
   behaves sufficiently like a list/dictionary/custom-object for its
   purposes.

   You may consider this an advantage or a disadvantage. To some extent
   it depends on the circumstances in which the function is used: if
   someone passes a not-quite-a-file (say) to a function expecting a
   file, is it more likely that this is because of a subtle bug that
   they'll be pleased to learn about early, or that they wanted the
   function to 'do the obvious thing' with it?

 - In particular, suppose your function expects a list and someone
   passes a string when they should have passed a list containing only
   that string. If you don't validate, the function is likely to process
   the string the same way as it would process a list containing a
   number of single-character strings.

   This might well lead to your program apparently completing
   successfully but giving the wrong result (which is usually the kind
   of error you most want to avoid).

 - If the function is going to be maintained together with its callers
   (rather than being part of the public interface to a library, say),
   then validation code is less likely to get in the way, because it
   should be easy to relax the checks if that turns out to be
   convenient.


-M-




More information about the Python-list mailing list