如何在python中强制静态类型

low*_*rin 11 python static-typing typing python-3.6

因为静态类型在python 3.6中可用.

是否可以强制python项目或python文件集的静态类型?

gle*_*oux 8

我认为你不能强迫,static typing但你可以使用检查器mypy.

根据The Zen of Python, by TimPeters你的第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!
Run Code Online (Sandbox Code Playgroud)

  • 静态(通常)比动态类型更好!这与效率无关,而与可读性有关。例如,“用户”是名称、号码、系统结构、数据库行还是其他内容?Java 从 Lisp 获得并赋予 C# 的重要思想是,脚本语言和高效语言之间不需要二分法。两者皆有可能。C# 尤其可以生成高效且易于使用的代码。 (2认同)
  • 静态类型是明确的,更具可读性并减少歧义。python 应该有一个模式来强制它(mypy 风格很好)。最终它可以在加载时使用此强制措施来生成优化的字节码 (2认同)

hsp*_*her 8

您可以annotations在Python3 中使用,这可能会帮助您获得静态类型的一些好处.

但是,如果要在Python中完全实施静态类型,那么它将不再是Python.它是一种鸭式的动态语言,因此会失去所有的动力.如果你真的打算使用静态类型的语言,最好不要使用Python.

  • 我喜欢它的动态性,但 Python 也在不断发展。当项目增长超过一定阈值时,类型检查开始变得非常重要,呈指数级增长。我认为该语言最终很有可能允许可选类型强制执行。 (3认同)
  • 我会选择可选的强制执行,类似于 mypy. 就我个人而言,我发现自己对近 80% 的代码进行了类型提示,因为使用好的 IDE 总是能带来巨大的回报。 (2认同)