def foo():
while <condition>:
do something
def bar():
for i in range(5):
do something
假设我在上面的文件名 test.py
中定义了两个函数。 python 有没有办法编写具有以下行为的函数?
import test
def uses_while(fn: Callable) -> bool:
(what goes here?)
>>> uses_while(test.foo)
True
>>> uses_while(test.bar)
False
我本质上需要以编程方式检查函数是否使用 while 循环,而不需要手动检查代码。我想过使用 pdb.getsourcelines() ,但是如果里面有注释或字符串中包含“while”一词,那么这不起作用。有什么想法吗?
最佳答案
import ast
import inspect
from typing import Callable
def uses_while(fn: Callable) -> bool:
nodes = ast.walk(ast.parse(inspect.getsource(fn)))
return any(isinstance(node, ast.While) for node in nodes)
在 Python 3.9+ 上,您必须将其更改为 from collections.abc import Callable
。
关于python - 如何检查python函数是否使用while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63718913/