Skip to content

Instantly share code, notes, and snippets.

@raymondberg
Created May 20, 2020 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raymondberg/113e96c5b461efc0a897c95573216e8c to your computer and use it in GitHub Desktop.
Save raymondberg/113e96c5b461efc0a897c95573216e8c to your computer and use it in GitHub Desktop.
Diabolical Import Randomizer
import os
import random
import re
import shutil
def all_python_files():
for basedir, _, filenames in os.walk("."):
for filename in filenames:
if filename.endswith(".py") and "gotcha" not in filename:
yield os.path.join(basedir, filename)
def randomize_imports(filename):
""" open file, identify import lines, update and overwrite """
import_lines = []
with open(filename, "r") as f, open("tmp_gotcha", "w") as g:
lines = f.readlines()
STATE = "new"
idx = -1
while idx < len(lines) - 1:
idx += 1
line = lines[idx]
if re.match("^import", line) or re.match("^from.*import", line):
if re.match(r".*\($", line):
sub_imports = []
while True:
idx += 1
next_line = lines[idx]
if re.match(r"^\)", next_line):
random.shuffle(sub_imports)
line += "".join(sub_imports) + next_line
break
else:
sub_imports.append(next_line)
import_lines.append(line)
STATE = "importing"
continue
elif STATE == "importing" and re.match("^$", line):
continue
elif STATE == "importing":
## shuffle and write
random.shuffle(import_lines)
for import_line in import_lines:
g.write(import_line)
g.write("\n")
STATE = "post_import"
import_lines = []
g.write(line)
shutil.move("tmp_gotcha", filename)
if __name__ == "__main__":
print([p for p in all_python_files()])
for filename in all_python_files():
randomize_imports(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment