Skip to content

Instantly share code, notes, and snippets.

@anapaulagomes
Created November 7, 2019 11:03
Show Gist options
  • Save anapaulagomes/af17f6180a1e68485be93c4840b78113 to your computer and use it in GitHub Desktop.
Save anapaulagomes/af17f6180a1e68485be93c4840b78113 to your computer and use it in GitHub Desktop.
Find methods and classes override by Python silently
"""Find class or methods override by Python silently."""
import argparse
import os
import re
from pprint import pprint
CLASS_OR_METHOD = r'\b(class|def) (.*)\('
CLASS_OR_METHOD_PATTERN = re.compile(CLASS_OR_METHOD)
exclude = [
'node_modules', 'venv', '.git', 'sql', 'docs',
'from_mommy_to_bakery.py', 'Pipfile', 'Pipfile.lock'
]
def _find_duplicated(content, only_class=False, only_method=False):
all_methods_and_classes = re.findall(CLASS_OR_METHOD_PATTERN, content)
unique = {}
duplicated = []
for method_or_class, name in all_methods_and_classes:
method_or_class_name = f'{method_or_class} {name}('
if unique.get(method_or_class_name):
if any([
only_class is False and only_method is False,
only_class and method_or_class == 'class',
only_method and method_or_class == 'def',
]):
duplicated.append(method_or_class_name)
else:
unique[method_or_class_name] = method_or_class_name
return duplicated
def check_files(directory='.', only_class=False, only_method=False):
excluded_by_gitignore = [
folder_or_file.strip()
for folder_or_file in open('.gitignore').readlines()
]
exclude.extend(excluded_by_gitignore)
for root, dirs, files in os.walk(directory, topdown=True):
dirs[:] = [
directory
for directory in dirs
if directory not in exclude
]
for file_ in files:
if file_ in exclude or not file_.endswith('.py'):
continue
file_path = f'{root}/{file_}'
content = open(file_path, 'r').read()
duplicated = _find_duplicated(content, only_class, only_method)
if duplicated:
print(file_path)
pprint(duplicated)
if __name__ == '__main__':
description = 'Find class or methods override by Python silently.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
'directory', help='Directory to be checked.',
default=os.getcwd(),
)
parser.add_argument(
'--class', dest='only_class', action='store_true',
)
parser.add_argument(
'--method', dest='only_method', action='store_true',
)
args = parser.parse_args()
check_files(args.directory, args.only_class, args.only_method)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment