[Python-Dev] Type hints -- a mediocre programmer's reaction

Steven D'Aprano steve at pearwood.info
Tue Apr 21 05:34:21 CEST 2015


On Mon, Apr 20, 2015 at 02:41:06PM -0400, Barry Warsaw wrote:
> On Apr 20, 2015, at 07:30 PM, Harry Percival wrote:
> 
> >tldr; type hints in python source are scary. Would reserving them for stub
> >files be better?
> 
> I think so.  I think PEP 8 should require stub files for stdlib modules and
> strongly encourage them for 3rd party code.

A very, very strong -1 to that.

Stub files are a necessary evil. Except where absolutely necessary, 
they should be strongly discouraged. A quote from the Go FAQs:

    Dependency management is a big part of software development 
    today but the “header files” of languages in the C tradition 
    are antithetical to clean dependency analysis—and fast 
    compilation.

    http://golang.org/doc/faq#What_is_the_purpose_of_the_project


Things that go together should be together. A function parameter and 
its type information (if any) go together: the type is as much a part 
of the parameter declaration as the name and the default. Putting them 
together is the best situation:

    def func(n: Integer): ...


and should strongly be prefered as best practice for when you choose to 
use type hinting at all. Alternatives are not as good. Second best is to 
put them close by, as in a decorator:

    @typing(n=Integer)  # Don't Repeat Yourself violation
    def func(n): ...


A distant third best is a docstring. Not only does it also violate DRY, 
but it also increases the likelyhood of errors:

    def func(n):
        """Blah blah blah

        blah blah blah

        Arguments:

             m:  Integer

        """

Keeping documentation and code in synch is hard, and such mistakes are 
not uncommon.

Putting the type information in a stub file is an exponentially more 
distant fourth best, or to put it another way, *the worst* solution for 
where to put type hints. Not only do you Repeat Yourself with the name 
of the parameter, but also the name of the function (or method and 
class) AND module. The type information *isn't even in the same file*, 
which increases the chance of it being lost, forgotten, deleted, out of 
date, unmaintained, etc.


-- 
Steve


More information about the Python-Dev mailing list