注释和文档字符串:语法、运行与工具读取
注释、普通字符串表达式和docstring分别说明,文档与实际实现保持一致。
学完这一章,你能够
- 注释、普通字符串表达式和docstring分别说明,文档与实际实现保持一致。
#注释和特殊开头行
字符串外的#开始注释到物理行末,字符串里的#仍是字符。多行说明可以逐行#,不必用三引号包住代码。正确的编码声明和Unix shebang虽然都以#起始,却在特定阶段有额外用途,不能说任何注释行都绝不影响运行环境。
用tokenize辨别COMMENT和STRING,再核对实际输出;不靠简单查找#删除文字,因为那会破坏网址、颜色或字符串内容。
三引号是字符串,不是块注释指令
三单引号与三双引号均创建字符串。同类三引号在字符串内没有嵌套注释语法,会结束当前字面量;不同引号可以作为内容,必要时转义。本章保留正常字符串和故意不匹配字符串的SyntaxError。
三引号中的#只是字符串字符,不是另一个可嵌套的注释。独立字符串可能成为docstring,f-string还能计算表达式,无效转义还可能在解析时失败;不能以没有给变量赋值就保证完全没有执行影响。
识别和读取docstring
模块、函数、类或方法的第一条字符串字面量语句可成为__doc__,三引号是惯用风格,并非只有三引号才可能构成docstring。后续独立字符串不自动成为该对象的运行时文档,f-string也不是普通docstring字面量。
__doc__保留原文布局,inspect.getdoc会按规则清理缩进,并可能查找继承文档;当前CPython对模块级类方法和某些函数局部类的查找结果可不同,本站分别记录,不承诺任意重写都能继承。help提供对象说明且返回None。不要把help打印的文字误认为其返回值。本站实际读取模块/函数/类/初始化方法/普通方法的文档,并捕获help输出。
带参数与异常的文档
函数文档应说明参数、默认操作、结果和可能异常,再用实际计算核对。本例提供相加、相减、相乘和非法操作ValueError四分支;类与其初始化、方法文档分别展示,不以类文档存在代替所有方法说明。
Google、Sphinx/reST与NumPy文档风格是不同标记约定,不改变Python解释器如何计算;选一种并保持一致。PEP257给出总体约定,具体工具支持要另查。-OO可移除文档字符串,本章用独立进程实际观察,不把文档当成任何运行模式下都存在的数据。
注释与文档接口
| 项目 | 作用 | 边界 |
|---|---|---|
| # | 字符串外到物理行末 | 编码/shebang有额外处理 |
| 三引号 | 创建字符串 | 没有同类块注释嵌套 |
| __doc__ | 运行时对象文档 | -OO可能移除,普通表达式不是docstring |
| help(obj) | 输出帮助,返回None | 不是把帮助文字作为返回值 |
| inspect.getdoc(obj) | 清理后的文档文本或None | 清理缩进,可能继承查找 |
| PEP257 | 文档总体约定 | 不是强制某一种参数标记风格 |
本章自编源码与运行范围
"""蓝色天空网 mbsky.com: runtime documentation for this owned module."""
from pathlib import Path
import sys,ast,inspect,io,tokenize,contextlib,subprocess
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
c=Checks()
def calculate(a,b,operation='sum'):
"""Calculate an owned two-number exercise.
Args:
a: First numeric input.
b: Second numeric input.
operation: sum, difference, or product.
Returns:
The selected arithmetic result.
Raises:
ValueError: When the operation is unsupported.
"""
if operation=='sum':return a+b
if operation=='difference':return a-b
if operation=='product':return a*b
raise ValueError('unsupported owned operation')
class Learner:
"""A learner on 蓝色天空网."""
def __init__(self,name):
"""Keep the supplied display name."""
self.name=name
def introduce(self):
"""Return the learner display sentence."""
return f'{self.name}在蓝色天空网学习。'
class DocumentedParent:
def action(self):
"""Parent documentation."""
class DocumentedChild(DocumentedParent):
def action(self):pass
def main():
code='text="# inside text" # actual comment\nprint(text)\n';tokens=list(tokenize.generate_tokens(io.StringIO(code).readline));c.eq('only real hash comment',[t.string for t in tokens if t.type==tokenize.COMMENT],['# actual comment']);c.eq('hash preserved in string',[t.string for t in tokens if t.type==tokenize.STRING],['"# inside text"'])
ns={};out=io.StringIO()
with contextlib.redirect_stdout(out):exec(compile(code,'<owned-comment>','exec'),ns)
c.eq('actual print ignores comment',out.getvalue(),'# inside text\n')
c.eq('first plain string docstring',ast.get_docstring(ast.parse('"one line also works"\nx=1\n')),'one line also works');c.eq('later plain string not module doc',ast.get_docstring(ast.parse('x=1\n"later"\n')),None)
content="'''first\n# still content\nlast'''";c.eq('triple hash is data',ast.literal_eval(content),'first\n# still content\nlast');c.eq('different triple quote content',ast.literal_eval("'''a \"\"\" b'''"),'a """ b')
c.raises('same triple quote does not nest',SyntaxError,lambda:compile("'''outer\n''' inner\n'''tail'''",'<owned-no-nesting>','exec'))
seen=[];scope={'seen':seen};exec(compile('f"{seen.append(1)}"','<owned-fstring-expression>','exec'),scope);c.eq('unused fstring has actual expression effect',seen,[1]);c.eq('fstring not docstring',ast.get_docstring(ast.parse('f"constant"')),None)
c.eq('own module doc available','蓝色天空网'in __doc__,True);c.eq('function doc present','Args:'in calculate.__doc__,True);c.eq('class doc',Learner.__doc__,'A learner on 蓝色天空网.');c.eq('init doc',Learner.__init__.__doc__,'Keep the supplied display name.');c.eq('method doc',Learner.introduce.__doc__,'Return the learner display sentence.');c.eq('actual class method',Learner('小蓝').introduce(),'小蓝在蓝色天空网学习。')
clean=inspect.getdoc(calculate);c.eq('getdoc cleans indentation','\nArgs:\n a:'in clean,True)
class Parent:
def action(self):
"""Parent documentation."""
class Child(Parent):
def action(self):pass
c.eq('override __doc__ actually None',Child.action.__doc__,None);c.eq('local class function resolution limit',inspect.getdoc(Child.action),None);c.eq('module class getdoc inherits',inspect.getdoc(DocumentedChild.action),'Parent documentation.')
c.eq('sum result',calculate(8,3),11);c.eq('difference result',calculate(8,3,'difference'),5);c.eq('product result',calculate(8,3,'product'),24);c.raises('documented invalid operation',ValueError,lambda:calculate(8,3,'quotient'))
help_output=io.StringIO()
with contextlib.redirect_stdout(help_output):returned=help(calculate)
c.eq('help returns None',returned,None);c.eq('help prints function signature',"operation='sum'"in help_output.getvalue(),True);c.eq('help prints actual doc','Raises:'in help_output.getvalue(),True)
own='"owned module doc"\ndef f():\n "owned function doc"\n return 3\nprint(repr(__doc__))\nprint(repr(f.__doc__))\n'
r=subprocess.run([sys.executable,'-I','-B','-X','utf8','-OO','-c',own],capture_output=True,text=True,encoding='utf8',timeout=20);c.eq('-OO process exit',r.returncode,0);c.eq('-OO removes module and function docs',r.stdout,'None\nNone\n')
c.finish('python3-comment',help_actual_output=help_output.getvalue(),getdoc_actual=clean,optimization_stdout=r.stdout,doc_styles='Google/reST/NumPy markup not separately rendered',source_code_executed=False)
if __name__=='__main__':main()
所需环境:本地 Python 环境
当前源码 SHA256:6fc628137e5f706ceb096ca1b99a5e9dabe1ac7f522aba4ff92381d9d5c0de1f
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。