gpt4 book ai didi

python - 按名称将函数的文档字符串复制到另一个函数

转载 作者:行者123 更新时间:2023-12-05 09:31:18 25 4
gpt4 key购买 nike

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

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

这是我目前所拥有的:

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__)

有什么有趣的点子吗?

最佳答案

经过一些测试,我了解到您可以这样做:

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

关于python - 按名称将函数的文档字符串复制到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68901049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com