Skip to content

Instantly share code, notes, and snippets.

@nlm
Created August 7, 2017 09:11
Show Gist options
  • Save nlm/6d46b56da98a99b22b6e3ab98b997455 to your computer and use it in GitHub Desktop.
Save nlm/6d46b56da98a99b22b6e3ab98b997455 to your computer and use it in GitHub Desktop.
Jinja2 custom code generator to detect unused variables
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