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

HHC*_*HHC 2 python automated-tests unit-testing bytecode python-3.x

def foo():
    while <condition>:
        do something

def bar():
    for i in range(5):
        do something
Run Code Online (Sandbox Code Playgroud)

假设我在一个文件名中定义了两个函数test.py。python 有没有办法编写具有以下行为的函数?

import test

def uses_while(fn: Callable) -> bool:
    (what goes here?)

>>> uses_while(test.foo)
True
>>> uses_while(test.bar)
False
Run Code Online (Sandbox Code Playgroud)

我本质上需要以编程方式检查函数是否使用 while 循环,而不需要手动检查代码。我想过使用 pdb.getsourcelines() ,但是如果里面有注释或字符串中包含“while”一词,那么这不起作用。有任何想法吗?

HHC*_*HHC 5

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)
Run Code Online (Sandbox Code Playgroud)

在 Python 3.9+ 上,您必须将其更改为from collections.abc import Callable.

  • @HHC 我认为问题是,如果他们使用 3.8 中的某些内容,而您在 3.6 中运行标记软件,例如,当他到达他不理解的部分时,“ast”包可能会失败 (2认同)