type notation 类型注释
PEP484作为核心,周边多个PEP构成的type hints矩阵,目前普及度并不高,上次看到相关应用还是cython加速,需要用到类型注解。
docstring是写给人看到,type hint更多是写给机器看的。
能够让IDE了解variable是什么类型,因此便于IDE进行自动补全。
在运行时会过滤掉类型信息。
谈到type就需要考虑到静态语言与动态语言孰优孰劣的问题。参见(英文原文,中文翻译),文中得出了静态语言比动态语言更好维护的结论,这也与reference2 中给出的type hint的优点一致:看代码要比写代码多得多,便于维护很重要。
It’s usually faster to write new code in a dynamically-typed language like Python because you don’t have to write out all the type declarations by hand. But when your codebase starts to get large, you’ll inevitably run into lots of runtime bugs that static typing would have prevented.
It’s not all-or-nothing. So you can start by declaring types in the places that are the most valuable without changing all your code.