Created
August 7, 2017 09:11
-
-
Save nlm/6d46b56da98a99b22b6e3ab98b997455 to your computer and use it in GitHub Desktop.
Jinja2 custom code generator to detect unused variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from jinja2.compiler import CodeGenerator | |
class CustomCodeGenerator(CodeGenerator): | |
def __init__(self, *args, **kwargs): | |
super(CustomCodeGenerator, self).__init__(*args, **kwargs) | |
self._vars_tracker = set() | |
def visit_Template(self, *args, **kwargs): | |
super(CustomCodeGenerator, self).visit_Template(*args, **kwargs) | |
if len(self._vars_tracker) > 0: | |
warn('unused variables: {0}'.format(', '.join(self._vars_tracker))) | |
def visit_Name(self, node, frame): | |
if node.ctx == 'store': | |
self._vars_tracker.add(node.name) | |
elif node.ctx == 'load': | |
self._vars_tracker.discard(node.name) | |
super(CustomCodeGenerator, self).visit_Name(node, frame) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment