如何在python注释中指定输入和输出数据类型?

2024-05-28 20:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经看到了一些标准,用于编写函数在Python中期望并返回的数据类型的注释。在哪一个是最佳实践上有共识吗?

我应该开始使用http://www.python.org/dev/peps/pep-3107/中的新功能吗?


Tags: 函数orgdev功能http标准wwwpep
3条回答

Python 3.5官方版typing

https://docs.python.org/3/library/typing.html

此更新使类型成为语言的实际部分。

示例:

#!/usr/bin/env python3

from typing import List

def f(x: int, ys: List[float]) -> str:
    return "abc"

# Good.
f(1, [2.0, 3.0])

# Bad.
f("abc", {}) # line 12

x = 1
x = "a" # line 15

y = [] # type: List[int]
y.append("a") # line 18

这段代码正常运行:Python 3.5默认情况下不强制输入。

但是,静态绒布可以使用它来诊断问题,例如:

sudo pip3 install mypy
mypy a.py

给出:

a.py:12: error: Argument 1 to "f" has incompatible type "str"; expected "int"
a.py:12: error: Argument 2 to "f" has incompatible type Dict[<nothing>, <nothing>]; expected List[float]
a.py:15: error: Incompatible types in assignment (expression has type "str", variable has type "int")
a.py:18: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"

像Pycharm这样的现有静态分析器已经可以解析Sphinx文档类型,但是这个语言更新提供了一种官方的规范化方法,这种方法可能会占上风。

狮身人面像1.8.2似乎还不支持它,但这只是时间问题:Python 3: Sphinx doesn't show type hints correctly

函数注释不是用于特定用途的,它们可以用于任何用途。

可以编写工具从注释中提取信息并执行任何您想要的操作,包括检查类型或生成文档。但是python本身并没有对这些信息做任何处理。您可以用于完全不同的目的,即提供将对参数调用的函数或声明可能的返回值字符串。

注释可以是任何对象:

def somefunc(param1: "string annotation", 
             param2: 151631,  
             param3: any_object): -> "some information here":

您可以使用以下方法检索对象:

print (somefunc.func_annotations)
{'param1': "string annotation", 
 'param2': 151631,  
 'param3': <object any_object>,
 'return': "some information here"}

PEP提供的用例建议:

  • 提供打字信息
    • 类型检查
    • 让ide显示函数期望并返回的类型
    • 函数重载/泛型函数
    • 外语桥梁
    • 适应
    • 谓词逻辑函数
    • 数据库查询映射
    • RPC参数封送处理
  • 其他信息
    • 参数和返回值文档

由于函数注释语法太新,因此它实际上不用于任何生产工具。

我建议用其他方法来记录。我使用epydoc生成文档,它可以从docstring中读取参数类型信息:

def x_intercept(m, b):
    """
    Return the x intercept of the line M{y=m*x+b}.  The X{x intercept}
    of a line is the point at which it crosses the x axis (M{y=0}).

    This function can be used in conjuction with L{z_transform} to
    find an arbitrary function's zeros.

    @type  m: number
    @param m: The slope of the line.
    @type  b: number
    @param b: The y intercept of the line.  The X{y intercept} of a
              line is the point at which it crosses the y axis (M{x=0}).
    @rtype:   number
    @return:  the x intercept of the line M{y=m*x+b}.
    """
    return -b/m

这个例子来自epydoc's website。它可以生成各种格式的文档,并且可以从类和调用配置文件生成良好的图形。

如果使用epydoc生成API文档,则有三种选择。

  • 电子文本。

  • 重新构造文本,RST。

  • JavaDoc表示法,看起来有点像epytext。

我建议使用RST,因为它可以很好地与sphinx一起生成包含API引用的整个文档套件。RST标记定义为here。可以指定的各种epydoc字段都是定义的here

例如。

def someFunction( arg1, arg2 ):
    """Returns the average of *two* (and only two) arguments.

    :param arg1: a numeric value
    :type arg1: **any** numeric type

    :param arg2: another numeric value
    :type arg2: **any** numeric type

    :return: mid-point (or arithmetic mean) between two values 
    :rtype: numeric type compatible with the args.
    """
    return (arg1+arg2)/2

相关问题 更多 >

    热门问题