Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self scanning code to prevent print statments

Tags:

python

I have a python project I'm working on whereby instead of print statements I call a function say() so I can print information while in development and log information during production. However, I often forget this and put print statements in the code by mistake. Is there anyway to have the python program read its own source, and exit() if it finds any print statements outside of the function say()?

like image 288
captainandcoke Avatar asked Jan 18 '13 01:01

captainandcoke


1 Answers

This can be done using the ast module. The following code will find any calls of the print statement and also of the print() function in case you are on Python 3 or Python 2 with the print_function future.

import ast

class PrintFinder(ast.NodeVisitor):
    def __init__(self):
        self.prints_found = []

    def visit_Print(self, node):
        self.prints_found.append(node)
        super(PrintFinder, self).generic_visit(node)

    def visit_Call(self, node):
        if getattr(node.func, 'id', None) == 'print':
            self.prints_found.append(node)
        super(PrintFinder, self).generic_visit(node)


def find_print_statements(filename):
    with open(filename, 'r') as f:
        tree = ast.parse(f.read())
    parser = PrintFinder()
    parser.visit(tree)
    return parser.prints_found

print 'hi'
for node in find_print_statements(__file__):
    print 'print statement on line %d' % node.lineno

The output of this example is:

hi
print statement on line 24
print statement on line 26

like image 100
ThiefMaster Avatar answered Oct 12 '22 00:10

ThiefMaster