我最近开始学习使用Python编程,在某些来源中我遇到了代码:
def f(x : int) -> str:
或
def f(x):
"""(int) -> str...."""
当我尝试第一个代码时,似乎没有限制函数的输入或输出。这是否意味着它们是为了使代码清晰明了,而使用它们中的任何一个都取决于个人喜好,还是我缺少某些东西?
这是否意味着它们是为了使代码清晰
是的,类型提示代码通常更容易阅读和理解。
您还可以使用第三方工具来检查您的代码。您可以使用两种工具:mypy和pyre。
如果您有一个名为example.py
的模块:
def foo(bar: int) -> str:
return str(bar)
foo("hello, world")
foo(1)
foo(b'\x00')
您可以这样检查:
$ mypy example.py
example.py:5: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
example.py:7: error: Argument 1 to "foo" has incompatible type "bytes"; expected "int"
Found 2 errors in 1 file (checked 1 source file)