Function parameter type safety?

Steven Bethard steven.bethard at gmail.com
Fri Jul 13 00:26:08 CEST 2007


Robert Dailey wrote:
> Is there a way to force a specific parameter in a function to be a
> specific type? For example, say the first parameter in a function of
> mine is required to be a string. If the user passes in an integer, I
> want to notify them that they should pass in a string, not an integer.

In Python, you generally don't want to do this. If I have code like::

     def foo(x):
         if not isinstance(x, basestring):
             raise ValueError('x must be a string')
         return x.split()

then if someone creates a string-like object that doesn't subclass from 
basestring, my code raises an exception even though the string-like 
object had a .split() method and would have worked perfectly. If you 
really feel like you need to give a specific error message, you could 
write it instead like::

     def foo(x):
         try:
             split = x.split
         except AttributeError:
             raise ValueError('x needs to have a split() method')
         return split()

But generally there's no reason to do that because the AttributeError 
itself would have said almost exactly the same thing.

Long story short: checking parameter types is un-Pythonic. Don't do it.

STeVe



More information about the Python-list mailing list