如何在函数标题或文档字符串中指定输入和输出的类型?

问题描述 投票:0回答:1

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

def f(x : int) -> str:

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

当我尝试第一个代码时,似乎没有限制函数的输入或输出。这是否意味着它们是为了使代码清晰明了,而使用它们中的任何一个都取决于个人喜好,还是我缺少某些东西?

python function definition
1个回答
0
投票

这是否意味着它们是为了使代码清晰

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

您还可以使用第三方工具来检查您的代码。您可以使用两种工具:mypypyre

如果您有一个名为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)
© www.soinside.com 2019 - 2024. All rights reserved.