Skip to content

Instantly share code, notes, and snippets.

@shaib
Forked from agmond/py3_fix_super_calls.py
Last active January 13, 2021 15:44
Show Gist options
  • Save shaib/8e718e664c375c41f015920884e48b29 to your computer and use it in GitHub Desktop.
Save shaib/8e718e664c375c41f015920884e48b29 to your computer and use it in GitHub Desktop.
Fix `super()` calls after migration to Python3

The following script fixes super() calls after migration from Python 2 to Python 3. The script edits the code automatically. Upon completion, the following steps are recommended:

  • Search for the regex super\([^\)] and fix manually those places (if needed)
  • Search for the regex super\(\s[^\)] and fix manually those places (if needed)
  • Run Flake8 and manually fix styling problems
import ast
import linecache
from pathlib import Path
root_path = Path('.')
files = root_path.glob('**/*.py')
class SuperVisitor(ast.NodeVisitor):
def __init__(self, filename, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filename = filename
self.current_class_name = None
self.interesting_super_lines = []
def visit_ClassDef(self, node):
self.current_class_name = node.name
for child_node in node.body:
self.generic_visit(child_node)
self.current_class_name = None
return node
def visit_Call(self, node):
if (
self.current_class_name
and hasattr(node, 'func')
and getattr(node.func, 'id', None) == 'super'
and hasattr(node, 'args')
and len(node.args) == 2
):
class_name_arg, self_arg = node.args
if getattr(class_name_arg, 'id', None) != self.current_class_name:
self.interesting_super_lines.append(node.lineno)
for child_node in ast.walk(node):
if child_node != node:
self.generic_visit(child_node)
return node
for filename in map(str, files):
with open(filename, 'r') as f:
source = f.read()
parsed = ast.parse(source, filename)
node_visitor = SuperVisitor(filename)
node_visitor.visit(parsed)
if node_visitor.interesting_super_lines:
print(filename, ":", node_visitor.interesting_super_lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment