2 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
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.

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
我編寫了一個(gè)簡(jiǎn)單的函數(shù),可以檢查作為參數(shù)給出的函數(shù)是否包含 while 循環(huán):
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
添加回答
舉報(bào)