如何在 Python 中强制静态输入?
How to force static typing in Python?
由于静态类型在 Python 3.6 中可用,是否可以为 Python 项目或一组 Python 文件强制静态类型?
我认为你不能强制静态类型,但你可以使用检查器作为 mypy
。
根据 Tim Peters 的 The Zen of Python 的第 2 行,您有 "Explicit is better than implicit." 静态类型是一件好事,但是 "Simple is better than complex." ...
$ 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 中使用 annotations
,这可能会帮助您获得静态类型的一些好处。
然而,如果在 Python 中完全强制执行静态类型,那么它将不再是 Python。 它是鸭子动态类型语言,并因此失去所有活力。如果你真的打算使用静态类型的语言,你最好不要使用 Python.
由于静态类型在 Python 3.6 中可用,是否可以为 Python 项目或一组 Python 文件强制静态类型?
我认为你不能强制静态类型,但你可以使用检查器作为 mypy
。
根据 Tim Peters 的 The Zen of Python 的第 2 行,您有 "Explicit is better than implicit." 静态类型是一件好事,但是 "Simple is better than complex." ...
$ 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 中使用 annotations
,这可能会帮助您获得静态类型的一些好处。
然而,如果在 Python 中完全强制执行静态类型,那么它将不再是 Python。 它是鸭子动态类型语言,并因此失去所有活力。如果你真的打算使用静态类型的语言,你最好不要使用 Python.