我已经看到了几种关于如何编写Python函数期望和返回的数据类型的评论标准。关于哪一个是最佳实践,是否有共识?如何在python注释中指定输入和输出数据类型?
http://www.python.org/dev/peps/pep-3107/是我应该为此使用的新功能吗?
我已经看到了几种关于如何编写Python函数期望和返回的数据类型的评论标准。关于哪一个是最佳实践,是否有共识?如何在python注释中指定输入和输出数据类型?
http://www.python.org/dev/peps/pep-3107/是我应该为此使用的新功能吗?
函数注释并非针对特定用途,它们可用于任何事情。
可以编写工具来从注释中提取信息并执行任何您想要的操作,包括检查类型或生成文档。但是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"}
使用情况的建议
由于功能注释语法是太新,但真的不用于任何生产工具。
我建议使用其他方法来记录它。我用epydoc的生成我的文档,并且它可以从文档字符串读取参数输入信息:
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文档,您有三种选择。
Epytext。
ReStructuredText,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
的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默认情况下不执行打字。
但然而,可以通过静态棉短绒用于diagnoze问题,如:
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的静态分析仪已经可以解析狮身人面像的文档类型,但这种语言更新提供了一个官方规范的方式,可能会占上风。
您可以详细说明在哪个版本的Python中添加了此语法吗? – 2009-01-28 10:57:44