2 回答

TA贡献1796条经验 获得超4个赞
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.

TA贡献1848条经验 获得超6个赞
我编写了一个简单的函数,可以检查作为参数给出的函数是否包含 while 循环:
import inspect
def test_while(func):
flag = False
body = inspect.getsourcelines(func)
string = ''.join(body[0]).replace(' ', '')
splited = string.split('\n')
for chain in splited:
if len(chain) > 0 and chain[0] is not '#':
if chain.startswith('while'):
flag = True
return flag
添加回答
举报