Python如何避免docstring重复参数说明且适配PyCharm悬浮提示
解决方案
首先明确结论:Python没有官方的docstring规范支持跨函数的参数描述引用,你提到的:see @method1.param.common_param:类语法属于自定义写法,PyCharm没有对应的解析逻辑,所以会出现你截图里的提示异常问题。
以下是可兼容PyCharm悬浮提示、避免重复编写参数说明的可行方案:
- 方案1:装饰器动态注入公共文档片段
提前定义重复的参数描述片段,通过装饰器在函数定义阶段批量替换到docstring中,PyCharm的静态扫描可以正常识别拼接后的完整文档:
后续需要修改公共参数描述时,只需修改# 预先定义公共参数的文档片段 _COMMON_PARAM_DOC = ":param common_param: The same parameter description" def inject_common_doc(func): if func.__doc__: # 替换docstring中的占位符 func.__doc__ = func.__doc__.replace("{{common_param}}", _COMMON_PARAM_DOC) return func @inject_common_doc def method1(common_param: str, param_coffee): """ This method make coffee. {{common_param}} :param param_coffee: Specific coffee parameter """ ... @inject_common_doc def method2(common_param: str, param_tea): """ This method make tea. {{common_param}} :param param_tea: Specific tea parameter """ ..._COMMON_PARAM_DOC一处即可同步到所有使用该装饰器的函数。 - 方案2:reStructuredText规范的间接说明
如果你不需要把参数描述直接嵌到当前docstring里,可以用reST的交叉引用语法,PyCharm支持跳转,悬浮时也能正常展示文本:
该方案不需要额外代码,但用户悬浮查看时不能直接看到完整参数描述,需要点击跳转才能查看详情。def method2(common_param: str, param_tea): """ This method make tea. :param common_param: 含义同 :meth:`method1` 的`common_param`参数 :param param_tea: Specific tea parameter """ ...
内容的提问来源于stack exchange,提问作者olive007
相关产品推荐
相关产品推荐

