Function parameter type safety?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 13 03:19:32 EDT 2007


Robert Dailey a écrit :
> Hi,
> 
> Is there a way to force a specific parameter in a function to be a
> specific type?

No, and that's considered a GoodThing(tm).

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

Document the fact that the function expects a string as it's first 
param. If someone pass an int, it's likely that he'll soon find out 
there's something wrong (either from an exception or from obviously 
incoherent results). This is usually enough.

If you're in the case that passing a non-string will not raise an 
exception in the function but just lead to strange results or raise 
somewhere else, you can eventually use an assertion to ease debugging - 
but don't get into the habit of systematically type-check functions 
arguments, this would be fighting against the language.

My 2 cents...



More information about the Python-list mailing list