Function parameter type safety?

Larry Bates larry.bates at websafe.com
Thu Jul 12 18:17:15 EDT 2007


Robert Dailey 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.
> 

There is, but be careful.  What about a string-like object, why would you want
to fail on that.  It is better to attempt to do whatever you want to do with the
string and catch the exception.

Possible solution that I don't really like, but meets your explicit requirement:

def foo(arg1):
    if isinstance(arg1, (basestring, unicode):

	print "is string"
    else:
        print "is NOT string"

    return


-Larry



More information about the Python-list mailing list