使用 inspect.getsourcelines 函数,我已经能够像这样获取 Python 函数的源代码:
import inspect
def some_decorator(x):
return x
@some_decorator
def foo():
print("bar")
print(inspect.getsourcelines(foo)[0])
此代码将函数的源代码行正确输出为列表:
['@some_decorator\n', 'def foo():\n', ' print("bar")\n']
但是,我只想要函数内部的代码,而不是整个函数声明。所以我只想要这个输出(还要注意正确的缩进):
['print("bar")\n']
我曾尝试使用切片和 strip 来删除前两行,然后删除缩进,但这不适用于许多函数,我不得不相信有更好的方法方式。
inspect 模块或我可以pip install 的其他模块是否具有此功能?
请您参考如下方法:
如果定义多于一行 和 使用注释(因为注释引入了额外的“:”),则接受的答案中的两个解决方案会中断。在下文中,我也会处理这种情况(但不包括已接受答案的第二个函数中包含的异步情况。
import inspect
from itertools import dropwhile
def get_function_body(func):
source_lines = inspect.getsourcelines(func)[0]
source_lines = dropwhile(lambda x: x.startswith('@'), source_lines)
line = next(source_lines).strip()
if not line.startswith('def '):
return line.rsplit(':')[-1].strip()
elif not line.endswith(':'):
for line in source_lines:
line = line.strip()
if line.endswith(':'):
break
# Handle functions that are not one-liners
first_line = next(source_lines)
# Find the indentation of the first line
indentation = len(first_line) - len(first_line.lstrip())
return ''.join([first_line[indentation:]] + [line[indentation:] for line in source_lines])
例如,应用于:
# A pre comment
def f(a, b: str, c='hello',
d: float=0.0, *args, **kwargs) -> str:
"""The docs"""
return f"{c} {b}: {a + d}"
print(get_function_body(f))
我明白了
"""The docs"""
return f"{c} {b}: {a + d}"
