【问题标题】:Copying the docstring of function onto another function by name按名称将函数的文档字符串复制到另一个函数
【发布时间】:2021-10-24 07:15:58
【问题描述】:

我希望按名称(使用装饰器)将函数的文档字符串复制到同一文件中。

我可以很容易地使用当前模块之外的函数来做到这一点,但是当涉及到同一个模块(或者更具体地说是同一个类)时我有点困惑

这是我目前所拥有的:

import inspect

def copy_doc(func_name: str):
    def wrapper(func):
        doc = ... # get doc from function that has the name as func_name
        func.__doc__ = doc
        return func
    retun wrapper

我正在寻找可以做以下两个例子的东西:

例 1:

def this() -> None:
    """Fun doc string"""
    return

@copy_doc('this')
def that() -> None:
    return

print(that.__doc__)

例 2:

class This:
    def foo(self) -> None:
        """Fun doc string"""
        return None

    @copy_doc('foo')
    def bar(self) -> None:
        return None

print(This().bar.__doc__)

有什么有趣的想法吗?

【问题讨论】:

  • 您可以将@copy_doc('this') 替换为@copy_doc(this) 并尝试func_name.__doc__
  • 没错,是的。仍然需要涵盖第二个示例,这是重要的一个:)

标签: python docstring


【解决方案1】:

经过一些测试,我了解到您可以执行以下操作:

from typing import Callable

def copy_doc(copy_func: Callable) -> Callable:
    """Use Example: copy_doc(self.copy_func)(self.func) or used as deco"""
    def wrapper(func: Callable) -> Callable:
        func.__doc__ = copy_func.__doc__
        return func
    return wrapper

class Test:
    def foo(self) -> None:
        """Woa"""
        ...
    
    @copy_doc(foo)
    def this(self) -> None:
        ...
    

print(Test().this.__doc__)

# Outputs:
> Woa

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 2012-02-22
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2010-10-27
    • 2015-12-23
    相关资源
    最近更新 更多