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

时间:2020-09-03 07:35:42

标签: 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”一词的注释或字符串,则该方法将不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

我写了一个简单的函数,可以检查作为参数给出的函数是否包含while循环:

var optionsBP= [
{
    id:1,
    score:0,
    text:'Strongly Dislike',
    isSelected:false
},
{
    id:2,
    score:1,
    text:'Dislike',
    isSelected:false
},
{
    id:3,
    score:2,
    text:'Unsure',
    isSelected:false
},
{
    id:4,
    score:3,
    text:'Like',
    isSelected:false
},
{
    id:5,
    score:4,
    text:'Strongly Like',
    isSelected:false
}
];
quesBank = [
{
    id:1,
    desc:'Build Kitchen Cabinets',
    options: optionsBP,
    name: 'res1',
    checked: 'false',
    selvalue: -1
},
{
    id:2,
    desc:'Lay Brock Or Tile',
    options: optionsBP,
    checked: 'false',
    name: 'res2',
    selvalue: -1
},
{
    id:3,
    desc:'Brick Tile3',
    options: optionsBP,
    name: 'res3',
    checked: 'false',
    selvalue: -1
},
{
    id:4,
    desc:'Brick Tile4',
    options: optionsBP,
    name: 'res4',
    checked: 'false',
    selvalue: -1
},
{
    id:5,
    desc:'Brick Tile5',
    options: optionsBP,
    name: 'res5',
    checked: false,
    selvalue: -1
},
{
    id:6,
    desc:'Brick Tile6',
    options: optionsBP,
    name: 'res6',
    checked: false,
    selvalue: -1
}
];
相关问题