Check header files for namespace usage To ensure there are no naming conflicts within our project (C++) I was tasked with writing a python script to check all of our header files for any occurrences of a using namespace ... within the file. If an occurrence is found, it's appended to a list then written to a log file. It's a fairly simple script, but I feel there could be some optimizations. This script is ran whenever someone commits to the repository.

"""
Checks all the header files in our project to ensure there
aren't occurrences of the namespace string.

AUTHOR: Ben Antonellis
DATE: April 4th, 2020
"""

import os

namespace: str = "using namespace"
working_directory: str = os.path.dirname(os.path.realpath(__file__));
occurrences: list = []

for file in os.listdir(working_directory):
    formatted_file = f"{working_directory}/{file}"
    with open(formatted_file, "r") as source_file:
        for line_number, line in enumerate(source_file):
            if namespace in line and file[-3:] != ".py":
                occurrences.append(f"NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {formatted_file}")

with open("logs/log.txt", "w") as log_file:
    for line in occurrences:
        log_file.write(line)
Working directory

os.path.dirname(os.path.realpath(__file__))


is not the current working directory. The current working directory is available via os.getcwd. Either you should call that instead, or maybe rename your variable.

Semicolons

are usually discouraged in Python, so you can drop one here:

working_directory: str = os.path.dirname(os.path.realpath(__file__));


pathlib

f"{working_directory}/{file}"


is better represented by making a Path and then using the / operator.

Overall

This approach is fragile. You're better off tapping into something like the LLVM/Clang AST, which actually understands how to parse all of the edge cases of C++.

Here is a suggestion that takes care of everything except the AST:

from pathlib import Path

NAMESPACE = 'using namespace'

log_file_name = Path('logs/log.txt')

if __name__ == '__main__':
    working_dir = Path.cwd()
    with log_file_name.open('w') as log_file:
        for prefix in ('h', 'c'):
            for file_name in working_dir.glob(f'*.{prefix}*'):
                with file_name.open() as source_file:
                    for line_number, line in enumerate(source_file):
                        if NAMESPACE in line:
                            log_file.write(f'NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {file_name}\n')


This also takes into account @AJNeufeld's feedback which is good.