It All Started with PEP484
1 | def greeting(name: str) -> str: |
Annotating types in a way similar to golang’s type annotations.
Type Hints in Python3
In Python3, you can refer to the following forms:
Class methods
1 | # File models/a.py |
No annotation is needed for the self variable, and one more thing: you can use a string 'b.B' to represent it.
Assignment && multiple variable assignment
1 | x = [] # type: List[Employee] |
For loops and With statements
1 | with frobnicate() as foo: # type: int |
How to Use This in Python2 Projects?
Actually a big part of writing this blog was to explain the feasibility of type annotations in Python2, because the projects I took over are all Python2, which doesn’t support Python3’s Type syntax, but I still want to use definite-typed code. The official documentation also explains this here.
1 | def embezzle(self, account, funds=1000000, *fake_receipts): |
Put the types of the function variables before the docstring, add # type:, and it will be automatically recognized as a type annotation.
For assignments and loop statements, refer to the Python3 approach.
What Do Type Hints Actually Bring
More powerful code completion. Whether you’re a VSCode or Vim user, Python’s code completion hints are quite weak. But after you add types,
jedi‘s workload is greatly relieved, and you’ll find that even Vim’s code hints become quite practical.I think most people also believe programs in strongly typed languages are easier to maintain than weakly typed ones; two of the reasons are: 1. compile-time errors, 2. definite types.
Code Complete has this passage:
The real world is a mess — that doesn’t mean your code has to be equally bad. View your system as a combination of an ideal world, the messy real world, and the interface from the former to the latter.

If you really love Python’s weak typing, I think it belongs at the positions interacting with the real world, used to embrace this
messy world. But in the ideal world you create yourself, there should be no objects of uncertain type.
Please have enough control over your own world.
Please Add the Types!!!
Whether or not you’re a backend programmer, when using Python, please annotate the types. Consider it a favor to
us poor masses — let getting to know a new variable start with seeing its type, okay?