import re def detect_unused_loop_variable(code): regex = re.compile( r"^(?P *)for (?P\S+) in .+:(?:\n(?P=indent) +((?P[^#\n]*(?P=id).*)|.*))*", re.MULTILINE, ) result = regex.search(code) if not result: return False if result.group("contains"): return False # print(result.group(0)) return True