gpt4 book ai didi

python - 在 lambda 中访问函数的 __doc__

转载 作者:行者123 更新时间:2023-12-04 13:24:11 24 4
gpt4 key购买 nike

一旦函数被包裹在 lambda 中,我想提取它的文档字符串。 .
考虑以下示例:

def foo(a=1):
"""Foo docstring"""
return a

dct = {
"a": foo,
"b": lambda: foo(2),
}

for k, v in dct.items()
print(k, v(), v.__doc__)
我得到:
a 1 Foo docstring
b 2 None
如何引用在“调用” lambda 时调用的函数一?
更新
感谢所有回答:
from functools import partial

def foo(a=1):
"""Foo docstring"""
return a

dct = {
"a": foo,
"b": partial(foo, 2),
}

for k, v in dct.items():
if hasattr(v, "func"):
print(k, v(), v.func.__doc__)
else:
print(k, v(), v.__doc__)
a 1 Foo docstring
b 2 Foo docstring

最佳答案

没有“好”的方法可以做到这一点。但是,技术上可以使用 inspect模块。这是一个非常脆弱和脆弱的实现,适合您获取 lambda 调用的第一个函数的文档字符串的用例:

import inspect
import re

def get_docstring_from_first_called_function(func):
# the inspect module can get the source code
func_source = inspect.getsource(func)

# very silly regex that gets the name of the first function
name_of_first_called_function = re.findall(r'\w+|\W+', func_source.split("(")[0])[-1]

# if the function is defined at the top level, it will be in `globals()`
first_called_function = globals()[name_of_first_called_function]
return first_called_function.__doc__


def foo(a=1):
"""Foo docstring"""
return a

b = lambda: foo(2)

print(get_docstring_from_first_called_function(b))
> Foo docstring
正如我所说,这个实现是脆弱的。例如,如果调用的第一个函数不在 globals 中,它会立即中断。 .但是,如果您发现自己陷入非常可怕的困境,您可能可以为您的用例组合一个解决方案。
但是,如果可能的话,您应该改用 functools
import functools

def foo(a=1):
"""Foo docstring"""
return a

b = functools.partial(foo, 2)

print(b.func.__doc__)

关于python - 在 lambda 中访问函数的 __doc__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69634071/

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