Why Python doesn't throws type exceptions with '-> type' functions definitions? [duplicate]

和自甴很熟 提交于 2021-02-08 06:02:27

问题


In other languages anything like the example throws a type error. Why not in Python?

>>> def foo(a:int) -> str:
    return a+1

>>> foo(5)
6

回答1:


Type hinting in Python is an optional addition to aid static code analysis and editors.

From the PEP 484 -- Type Hints specification:

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

and

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

Note that type hints are a very new addition to Python, and the PEP is intended to aid in coordination, not to force runtime type checking on the language.

Python is not a statically typed language, it is still very much dynamically typed. You may be confusing this feature with type declarations in statically typed languages.

In future, it may be possible that Python adds support for a strict mode (similar to how Hack does this), but that's not on the table right now.



来源:https://stackoverflow.com/questions/38892779/why-python-doesnt-throws-type-exceptions-with-type-functions-definitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!