What's the difference between type hinting in 3.3 and 3.5?

2.9k views Asked by At

I keep hearing how type hinting will be a new feature in 3.5, but that makes me wonder what the arrow indicator (->) was in 3.3?

You can see it in the 3.3 grammar spec here, which I found from this question asked 2 years ago.

I'm wondering, did type hinting exist before, but in a limited fashion, and 3.5 is bringing more major support? Or is my understanding of type hinting incorrect, and it actually means something else?

1

There are 1 answers

5
Martijn Pieters On BEST ANSWER

The -> is used for annotations. One of the use cases for annotations is type hinting.

Python 3.0 added annotations, Python 3.5 builds on that feature by introducing type hinting, standardising the feature.

The relevant PEP (Python Enhancement Proposals) are:

Annotations are just syntax, type hinting is specific functionality.

You can use the syntax for anything you like, like inline documentation:

def documentation(self: "the instance", arg1: "first argument") -> "nothing is returned":
    pass

All that the syntax does is attach that extra information you provided to the function object:

>>> def documentation(self: "the instance", arg1: "first argument") -> "nothing is returned":
...     pass
... 
>>> documentation.__annotations__
{'return': 'nothing is returned', 'arg1': 'first argument', 'self': 'the instance'}

The Type Hinting specification specifies how you could use those annotations to say something about what type each argument should be and what is returned. It is a specific application of annotations in that it defines how to interpret the annotations.

The Type Hinting PEP explicitly states it is not meant to be the only use of annotations:

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

Type hinting remains entirely optional, it is not nor will it ever be required that you use it. Again quoting the PEP:

While the proposed typing module will contain some building blocks for runtime type checking -- in particular the get_type_hints() function -- third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

Emphasis in the original.

You can install the typing module to add type hinting to earlier Python 3.x versions.