[Python-Dev] Type hints -- a mediocre programmer's reaction
Steven D'Aprano
steve at pearwood.info
Tue Apr 21 16:06:54 CEST 2015
On Tue, Apr 21, 2015 at 03:08:27PM +0200, Antoine Pitrou wrote:
> On Tue, 21 Apr 2015 22:47:23 +1000
> Steven D'Aprano <steve at pearwood.info> wrote:
> >
> > Ironically, type hinting will *reduce* the need for intrusive,
> > anti-duck-testing explicit calls to isinstance() at runtime:
>
> It won't, since as you pointed out yourself, type checks are purely
> optional and entirely separate from compilation and runtime evaluation.
Perhaps you are thinking of libraries, where the library function has to
deal with whatever junk people throw at it. To such libraries, I believe
that the major benefit of type hints is not so much in proving the
library's correctness in the face of random arguments, but as
documentation. In any case, of course you are correct that public
library functions and methods will continue to need to check their
arguments. (Private functions, perhaps not.)
But for applications, the situation is different. If my application
talks to a database and extracts a string which it passes on to its own
function spam(), then it will be a string. Not a string-like object. Not
something that quacks like a string. A string. Once the type checker is
satisfied that spam() always receives a string, then further isinstance
checks inside spam() is a waste of time. If spam()'s caller changes and
might return something which is not a string, then the type checker
will flag that.
Obviously to get this benefit you need to actually use a type checker. I
didn't think I needed to mention that.
--
Steve
More information about the Python-Dev
mailing list