Skip to content

Instantly share code, notes, and snippets.

@millerdev
Last active August 23, 2019 15:44
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 millerdev/f71648c1a9690cfca7c8b7c049867cfc to your computer and use it in GitHub Desktop.
Save millerdev/f71648c1a9690cfca7c8b7c049867cfc to your computer and use it in GitHub Desktop.
Remove __future__ imports from Python files
#! /usr/bin/env python
"""Remove __future__ imports from Python files
Acts on *.py files in the current directory and all subdirectories.
Only removes lines in which all imported names are in KNOWN_FUTURES.
Public URL of this script:
https://gist.github.com/millerdev/f71648c1a9690cfca7c8b7c049867cfc
"""
import os
from os.path import join
FUTURE = "from __future__ import "
KNOWN_FUTURES = {
"absolute_import",
"division",
"print_function",
"unicode_literals",
"with_statement",
}
def main():
print("removing future imports from...")
for dirpath, dirnames, filenames in os.walk("."):
for name in list(dirnames):
if name.startswith("."):
dirnames.remove(name)
for name in filenames:
if name.endswith(".py"):
rm_future(join(dirpath, name))
def rm_future(path):
future = FUTURE
lines = []
found = False
with open(path, encoding="utf-8") as f:
for line in f:
if future in line:
if is_known_future(line):
found = True
else:
print("skipping unknown future:", line.strip(), "in", path)
lines.append(line)
else:
lines.append(line)
if found and lines:
print(path)
assert "\n" in lines[0], repr(lines[0])
with open(path, encoding="utf-8", mode="w") as f:
f.write("".join(lines))
def is_known_future(line):
if "#" in line:
line = line[:line.index("#")]
names = {p.strip() for p in line.replace(FUTURE, "").split(",")}
return not names - KNOWN_FUTURES
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment