Millet Porridge

English version of https://corvo.myseu.cn

0%

Some Practice with Python's Type System

It All Started with PEP484

1
2
def greeting(name: str) -> str:
return 'Hello ' + name

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
2
3
4
5
6
# File models/a.py
from models import b
class A(Model):
def foo(self, b: 'b.B'): ...

def bar(self, a: 'A'): ...

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
2
x = []                # type: List[Employee]
x, y, z = [], [], [] # type: List[int], List[int], List[str]

For loops and With statements

1
2
3
4
5
6
7
with frobnicate() as foo:  # type: int
# Here foo is an int
...

for x, y in points: # type: float, float
# Here x and y are floats
...

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
2
3
4
def embezzle(self, account, funds=1000000, *fake_receipts):
# type: (str, int, *str) -> None
"""Embezzle funds from account using fake receipts."""
<code goes here>

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

  1. 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.

  2. 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.

  3. 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.

Code Like

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?