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

标签 python python-3.x unit-testing automated-tests bytecode

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/

相关文章:

python-3.x - 如何在本地对 python 3 应用程序引擎应用程序进行单元测试?

python - 使用请求正文的单元测试 bottle py 应用程序导致 KeyError : 'wsgi.input'

python - 如何将时间显示为 0.01 秒?

python - 在 Python 中将整数转换为二进制

Python+Pandas+Dataframe+CSV : Code removes all rows from a dataframe instead of specified ones

python - 如何填充列表中的值并将其转换为数据帧?

python-3.x - 如何删除python中变量的最后一个字符?

python - 为什么 easygui 在传递包含带嵌入空格的字符串的元组时插入大括号?

javascript - D3 仅加载一个单元格的数据

Powershell 单元测试用例