Skip to content

Instantly share code, notes, and snippets.

@bbelderbos
Created May 22, 2023 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbelderbos/f408adeb88c6bb4c66638231ac36aac9 to your computer and use it in GitHub Desktop.
Save bbelderbos/f408adeb88c6bb4c66638231ac36aac9 to your computer and use it in GitHub Desktop.
import ast
from pathlib import Path
import sys
def check_for_else_in_module(module_path):
with open(module_path, "r") as file:
try:
tree = ast.parse(file.read())
except SyntaxError:
print(f"Error parsing {module_path}. Skipping.")
return
for node in ast.walk(tree):
if isinstance(node, (ast.For, ast.While)):
if node.orelse:
print(
f"Found 'for...else' or 'while...else' construct in {module_path} L{node.lineno}-{node.end_lineno}"
)
break
# Directory path to search for Python files
directory_path = sys.argv[1]
# Iterate over all Python files in the directory and its subdirectories
for file_path in Path(directory_path).glob("*/*.py"):
if "venv" in str(file_path) or ".tox" in str(file_path):
continue
check_for_else_in_module(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment