在函数头或文档字符串中指定输入和输出类型如何工作?

How does specifying type of input and output in function header or docstring work?

我最近开始使用 Python 学习编程,在某些资源中我遇到了代码:

def f(x : int) -> str:

def f(x):
    """(int) -> str...."""

当我尝试第一个代码时,它似乎没有限制函数的输入或输出。这是否意味着它们是为了代码清晰,使用它们取决于个人喜好还是我遗漏了什么?

does that mean they are for code clarity

是的,类型提示代码通常更易于阅读和理解。

您还可以使用第三方工具来检查您的代码。为此,您可以使用两种工具:mypy, and 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)