You need to enable JavaScript to run this app. 如何在函数内部不指定函数名的情况下打印该函数的__doc__文档字符串
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数内部不指定函数名的情况下打印该函数的__doc__文档字符串

解决方案

有两种常用的实现方式,无需在函数内部硬编码函数名即可获取自身的__doc__属性:

方案1:运行时动态查询当前函数(适合临时场景)

通过inspect模块和gc模块配合,查询当前运行的函数对象,兼容性强,支持嵌套函数场景:

import inspect
import gc

def square(n):
    '''Takes in a number n, returns the square of n'''
    # 获取当前栈帧的代码对象
    frame = inspect.currentframe()
    # 遍历找到持有该代码对象的函数本身
    current_func = next(
        obj for obj in gc.get_referrers(frame.f_code) 
        if inspect.isfunction(obj) and obj.__code__ is frame.f_code
    )
    print(current_func.__doc__)
    return n ** 2

如果你的函数是顶级函数(不是嵌套在其他函数/类里的),可以省略gc查询,写法更简单:

import inspect

def square(n):
    '''Takes in a number n, returns the square of n'''
    current_func = globals()[inspect.currentframe().f_code.co_name]
    print(current_func.__doc__)
    return n ** 2

方案2:装饰器预注入(适合高频调用场景)

用装饰器在函数定义阶段就把自身的__doc__注入到参数里,运行时不需要额外查询,性能接近原生调用:

from functools import wraps

def inject_self_doc(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(func.__doc__, *args, **kwargs)
    return wrapper

@inject_self_doc
def square(self_doc, n):
    '''Takes in a number n, returns the square of n'''
    print(self_doc)
    return n ** 2

注意事项

  • 函数内部直接写__doc__默认读取的是当前模块的文档字符串,不是当前函数的,所以无法直接使用。
  • 动态查询方案会有一定性能开销,不适合在每秒调用上万次的高频逻辑里使用。

内容的提问来源于stack exchange,提问作者Allan Xu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 18:15:08