蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-comment.py
python3-comment.py63 行
"""蓝色天空网 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 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-comment.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-comment.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习