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