如何检查 python 函数是否使用 while 循环?

How to check if a python function uses a while loop?

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

我写了一个简单的函数,可以检查作为参数给出的函数是否包含 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