[英]Conveying docstrings for certain python functions
我有一种通用的docstrings格式,制作函数时会遵循这种格式。 我对函数的功能进行了总结,然后简要解释了该函数用于输入什么类以及输出什么类。
def cuberoot4u(number):
"""Returns the cube root of number.
cuberoot4u(float) -> float
"""
return pow(number, 1/3)
因此,在这种情况下,cuberoot4u接受输入的浮点数,然后返回输出的浮点数。
如果函数将.txt文件作为输入并以字符串形式输出内容,那么我该如何最好地使用docstrings向用户传达函数需要哪种输入类型?
def getText(filename):
"""Reads the file filename and returns the content.
getText(?????) -> str
"""
fd = open(filename)
text = fd.read()
fd.close()
return text
最好说出getText(filename.txt) -> str
还是有一个特定的类名,就像字符串是'str'和整数是'int'一样?
另外,对于未明确定义输出的函数,例如以下示例,该怎么办:
def commandmenu():
"""Begin some random menu which does stuff.
commandmenu() -> ??????
"""
while 1:
someuserinput = input("Enter a command: ")
if someuserinput == 'this':
pass
elif someuserinput == 'that':
pass
else:
print('u suck')
return None
因此,在这种情况下,进入功能不会产生任何初始输出,因为它会在执行某项操作之前导致用户的输入。 什么最适合????? 这样的功能是否变得越来越细致,并可能根据向用户的提示等导致多种不同的输出?
您碰到了抽象中通常被称为漏洞的地方 。 在您的情况下,对于每个函数指定参数类型的抽象足以对其进行记录。 大多数语言(或也许所有语言),尤其是Python,都没有足够强大的类型系统来使其成为可能。
考虑一个与第一个函数相似的函数,但是要计算平方根:
def squareroot4u(number):
"""Returns the cube root of number.
squareroot4u(float) -> float
"""
return pow(number, 1/2)
显然,仅当number
为非负数时,返回类型才为float
,否则应为complex
。 Python(与某些面向科学的语言不同)没有针对非负数的单独类型,因此您必须另外指定执行它的协定 :
def squareroot4u(number):
"""Returns the cube root of number.
squareroot4u(number: float) -> float
precondition: number >= 0
raises ValueError otherwise
"""
return pow(number, 1/2)
我个人使用Sphinx
进行记录,其格式看起来像
def squareroot4u(number):
"""Returns the cube root of number.
:param number: a non-negative number, raises ``ValueError`` otherwise
:type number: ``float``
:return: square root of the input
:rtype: ``float``
"""
return pow(number, 1/2)
对于第二个功能:
def getText(filename):
"""Reads the file filename and returns the content.
:param filename: a path to a text file
(raises ``WhateverError``/blows ups the monitor otherwise)
:type filename: ``str``
:returns: file contents
:rtype: ``str``
"""
请注意,当可以从上下文推断出Python文档字符串中的类型时,通常会忽略它们(例如,除了str
, filename
还能是什么?)
现在,有了第三个功能,除了类型和合同外,您还有副作用 。 这些应该记录在功能的一般说明中(如果它们是运行此功能的重点),或者记录在注释/警告中(如果它们只是要记住的内容)。 例如(再次使用Sphinx
语法):
def commandmenu():
"""Begin some random menu which does stuff.
Shows an input prompt and awaits user input.
.. warning::
May or may not randomly format your hard drive during full moon.
"""
在其他语言(例如Haskell)中,某些副作用可以表示为类型(monad)并进行静态检查。 例如,标准库中的getText
有一个类似的函数,其类型为
readFile :: FilePath -> IO String
与String
相对,这意味着它对参数执行一些纯操作(也就是说,对于相同的输入始终返回相同的输出,并且没有副作用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.