【问题标题】:How does specifying type of input and output in function header or docstring work?在函数头或文档字符串中指定输入和输出的类型如何工作?
【发布时间】:2020-03-30 13:36:01
【问题描述】:

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

def f(x : int) -> str:

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

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

【问题讨论】:

  • Type 只是一个提示,就像mypy 工具会检查代码类型,你总是可以传递 anu 数据类型,这是 python ;)
  • 第一个例子见stackoverflow.com/q/32557920/3001761。 IDE 和其他工具使用这些提示。

标签: python function definition


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 2016-03-03
    • 1970-01-01
    • 2021-07-18
    • 2020-01-25
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多