Thoughts on using isinstance

Neil Cerutti horpner at yahoo.com
Wed Jan 24 09:23:06 EST 2007


On 2007-01-24, abcd <codecraig at gmail.com> wrote:
> In my code I am debating whether or not to validate the types of data
> being passed to my functions.  For example
>
> def sayHello(self, name):
>     if not name:
>         rasie "name can't be null"
>     if not isinstance(name, str):
>         raise "name must be a string"
>     print "Hello " + name
>
> Is the use of isinstance a "bad" way of doing things?  is it a
> "heavy" operation?  for example, if I use this in each function
> validate input will it slow things down a lot?
>
> just curious how you might handle this type of situation (other
> than not validating at all).

Validation of parameters is an excellent idea, but *not*
validation of datatypes. The problem is that sayHello can
function properly with many more objects than just strings, if
you write it differently. The following version accepts any
iterable over strings.

def sayHello(self, name):
  it = iter(name)
  print "Hello", ''.join(it)

It still lacks validation. But to validate a name you will need
to conceive a set of regular strings that contains every name
you'd like to accept. Names probably aren't worth validating,
although you might reasonably reject a few things, like the empty
string.

-- 
Neil Cerutti



More information about the Python-list mailing list