自从Python 3.6提供静态类型以来,是否可以强制对Python项目或一组Python文件进行静态类型化?
我认为你不能强制使用静态类型,但可以使用检查器,如 mypy
。
根据 Tim Peters 在《Python之禅》中第2行的说法,“显式优于隐式”。静态类型是一件好事,但“简单胜于复杂”...
$ python3.6
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
您可以在Python3中使用注释
,这可能会帮助您获得一些静态类型的好处。
然而,如果完全强制执行静态类型,则它不再是Python。 它是一种鸭子类型的动态语言,并且作为结果将失去所有动态性。 如果您真的想使用静态类型的语言,最好不要使用Python。
i
指定int
类型,但传递错误的参数、错误的顺序等一直是让我头痛的问题来源。 - j4hangir
'this is ' + <int>
引发错误)。对于我来说(Python 3.6.1),def f(s: str) -> str: return 0
然后调用f(0)
不会引发TypeError。 - Artyer