比如:
black . # 帮你添加空格,看起来好看
flake8 # 检查不规范的地方
然后会检查出代码不规范的地方,进而修改,比如下面这样的
所以要了解这个东西的规范,
来源:https://www.python.org/dev/peps/pep-0257/
有好人翻译了重点的一部分,感谢:PEP 257 文档字符串规范总结
不过我还是都看看好了
docstring是一种出现在模块、函数、类或者方法定义的第一行说明的字符串,这种docstring就会作为该对象的__docs__
属性。
从规范角度来说,所有的模块都应该有docstrings,那些从模块中引入的函数和类也要有docstrings。公有方法(包括__init__
构造器)也要有docstring。对于一个包来说,包的说明文档可能就来自__init__
文件中的docstring.
例如:
import collections
help(collections)
Python代码中其他地方出现的字符串也可以作为文档,但是其不会被Python字节编码器识别,也就无法作为运行时对象属性(也就无法被分配给__doc__
方法),但是有两种额外类型的docstrings可以被软件工具提取。
__init__
方法最开始地方简单的赋值语句之后的字符串,被称为“属性说明文档” (attribute docstrings)参考PEP 258,查看关于属性文档和附加文档的详细说明
为了保证一致性,
"""your docstring"""
。r"""your raw docstring"""
。u"""your Unicode docstring """
。python的docstring有两种,一种是单行,一种是多行(就是字面意思,有的注释文档是写在一行,有的需要回车,写成多行)
单行docstring
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...
注意:
"Do this",
"Return that"
,这个函数是用来干嘛的,函数参数如何,函数返回什么,不应该写其他无关内容。def function(a, b):
"""function(a, b) -> list"""
赖好应该是这样的:def function(a, b):
"""Do X and return a list."""
多行docstring
usage
信息,比如脚本被不正确的调用,或者还使用-h
参数时,就会打印出这个信息。
示例1:
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
...
示例2:
class Variable:
"""
Attributes:
history (:class:`History` or None) : the Function calls that created this variable or None if constant
derivative (variable type): the derivative with respect to this variable
grad (variable type) : alias for derivative, used for tensors
name (string) : a globally unique name of the variable
"""
def __init__(self, history, name=None):
global variable_count
assert history is None or isinstance(history, History), history
self.history = history
self._derivative = None
# This is a bit simplistic, but make things easier.
variable_count += 1
self.unique_id = "Variable" + str(variable_count)
# For debugging can have a name.
if name is not None:
self.name = name
else:
self.name = self.unique_id
self.used = 0
def requires_grad_(self, val):
"""
Set the requires_grad flag to `val` on variable.
Ensures that operations on this variable will trigger
backpropagation.
Args:
val (bool): whether to require grad
"""
self.history = History()
来源:https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings
直接看模板就好了
如果是一个模块,那么文件的最开始,应该有类似以下内容:
"""A one line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.FunctionBar()
"""
如果是函数和方法,那么其docstring应该类似下面:
def fetch_smalltable_rows(table_handle: smalltable.Table,
keys: Sequence[Union[bytes, str]],
require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
"""Fetches rows from a Smalltable.
Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.
Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: If True only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}
Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).
Raises:
IOError: An error occurred accessing the smalltable.
"""
class SampleClass:
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam: bool = False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
minitorch/slides-master/docs/slides+build2/module0.1.html#/14