Thoughts on using isinstance

Bruno Desthuilliers bruno.desthuilliers at websiteburo.com
Wed Jan 24 09:40:27 EST 2007


abcd a écrit :
> 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? 

Mostly, yes. Python is dynamically typed (well, it's dynamic all the 
way...), and fighting against the language is a bad idea.

Also, since the use of an object of non-compatible type would usually 
raise an exception (and while we're at it, avoid using strings as 
exceptions - better to use some Exception class), you don't actually 
gain anything.

> just curious how you might handle this type of situation (other than
> not validating at all).

There are mostly 2 cases :
1/ you're getting data from the outside world. Here, you have to be 
*very* careful, and you usually need more than simple validation. Good 
news is that we have modules like FormEncode designed to handle this case.

2/ you're getting 'data' from within your Python program. If you 
correctly applied 1/, whatever comes in should be ok - that is, unless 
you have a programmer error !-). But then, you'll usually have a nice 
exception and traceback (or better unit tests failures), so you can fix 
the problem immediatly.

Now there are *a few* corner cases where it makes sens to check what has 
been passed to a function - either because there are very strict and 
stable requirements here, or because the function can accept different 
kinds of objects, but needs to handle them in distinct ways.

MVHO is that the less code the better. As a matter of fact, trying to 
'protect' your function, you introduced a syntax error, that would not 
have been here if you had just wrote the simplest thing:

def say_hello(who):
   print "Hello", who

My 2 cents...



More information about the Python-list mailing list