Thoughts on using isinstance

Steve Holden steve at holdenweb.com
Wed Jan 24 08:35:08 EST 2007


abcd 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).
> 
> thanks
> 
The "Python way" is to validate by performing the operations you need to 
perform and catching any exceptions that result. In the case of your 
example, you seem to be saying that you'd rather raise your own 
exception (which, by the way, should really be a subclass of Exception, 
but we will overlook that) that relying on the interpreter to raise a 
ValueError or a TypeError. Is there really any advantage to this? You 
increase your code size and add *something* to execution time with 
little real purpose.

People coming to Python after C++ or some similar language that allows 
or requires parameter type declarations often don't feel comfortable 
taking this direction to start with, but  it works well for most of us.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com



More information about the Python-list mailing list