Type Hinting vs Type Checking and Preconditions

Florian Diesch diesch at spamfence.net
Fri Mar 10 13:25:12 EST 2006


"Tom Bradford" <bradford653 at gmail.com> writes:

> Let me first say that I'm sure that this subject has come up before,
> and so forgive me for beating a dead horse.  Secondly, let me say that
> Python's strength is its dynamic nature, and I don't believe that it
> should ever require a precondition scaffolding. With that said, I do
> believe that something like type hinting would be beneficial to the
> Python community, both for tool enablement and for disambiguous
> programming.
>
> Here is what I mean.  The following function, though conventionally
> indicating that it will perform a multiplication, will yield standard
> Python behaviors if a string value is passed to it:
>
> def multiplyByTwo(value):
>     return value * 2
>
> Passing 14 to it will return 28, whereas passing "14" to it will return
> "1414".  Granted, we know and accept that this is Python's behavior
> when you multiply two values, but because we don't (and shouldn't have
> to) know the inner workings of a function, we don't know that the types
> of the values that we pass into it may adversly affect that results
> that it yields.
>
> Now, on the other hand, if we were to introduce a purely optional type
> hint to the function prototype, such as follows:
>
> def multiplyByTwo(value:int):
>     return value * 2
>
> The python interpreter could do the work of casting the incoming
> parameter to an int (if it is not already) before it is multipled,
> resulting in the desired result or a typecasting error otherwise.
> Furthermore, it could do it more efficiently than a developer having to
> put conditional code at the beginning of traditionally typecasting
> functions.

What's the advantage? Instead of "multiplication may not do what I want
with some classes" you got "casting to int may not do what I want
with some classes". 
Passing a float now returns a much more counterintuitive result than 
passing a string in the old function.
And it's not working anymore with classes which you can not cast to int 
but implement multiplication.

In any case you have to document what exactly your function is doing and
the user has to read this documentation.



   Florian
-- 
Emacs doesn't crash!  It contains very little C, so there's very
little reason to have it crash. [Pascal Bourguignon in gnu.emacs.help]



More information about the Python-list mailing list