The other day I learned how to test if certain code uses a list comprehension:
import ast
import inspect
from collections.abc import Callable
def uses_list_comprehension(func: Callable) -> bool:
# https://stackoverflow.com/a/35150363
src = inspect.getsource(func)
program = ast.parse(src)
list_comps = [
node for node in ast.walk(program)
if type(node) is ast.ListComp
]
return len(list_comps) > 0
def func1():
return [
i for i in range(5)
]
def func2():
print("hello")
print(uses_list_comprehension(func1)) # True
print(uses_list_comprehension(func2)) # False
#ast