Function parameter type safety?

Dave Baum Dave.Baum at
Fri Jul 13 00:42:34 CEST 2007

In article <1184277163.803229.318660 at>,
 Robert Dailey <rcdailey at> wrote:

> Hi,
> 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.

At present, there isn't any built-in way to do this (see the recent 
thread "PEP 3107 and stronger typing" for a long discussion).

However, you can use assert and isinstance() to check it manually:

def foo(a):
   assert isinstance(a, str), "argument 'a' must be a string"

I wouldn't advocate getting carried away with this pattern since it 
precludes your function from working with duck typing and defeats some 
of the dynamic nature of Python.  On the other hand, without such checks 
the resulting exceptions from assuming an argument is one type when it 
is another can be a bit misleading.


More information about the Python-list mailing list