diff options
author | David Lord <davidism@gmail.com> | 2021-04-09 16:49:55 -0700 |
---|---|---|
committer | David Lord <davidism@gmail.com> | 2021-04-10 08:58:43 -0700 |
commit | c8db6c6313e90a47da92722f60010a6ada2e8644 (patch) | |
tree | e63287a1343c4bc02d5d8b2ae641e2ed217c0972 | |
parent | 94b381da2343423de0bac5ec90c6cf4497f213ce (diff) | |
download | jinja2-c8db6c6313e90a47da92722f60010a6ada2e8644.tar.gz |
extract common code for import/from nodes
-rw-r--r-- | src/jinja2/compiler.py | 33 |
1 files changed, 13 insertions, 20 deletions
diff --git a/src/jinja2/compiler.py b/src/jinja2/compiler.py index 38d4fd3..7a15d80 100644 --- a/src/jinja2/compiler.py +++ b/src/jinja2/compiler.py @@ -977,15 +977,11 @@ class CodeGenerator(NodeVisitor): if node.ignore_missing: self.outdent() - def visit_Import(self, node, frame): - """Visit regular imports.""" - self.writeline(f"{frame.symbols.ref(node.target)} = ", node) - if frame.toplevel: - self.write(f"context.vars[{node.target!r}] = ") - + def _import_common(self, node, frame): self.write(f"{self.choose_async('await ')}environment.get_template(") self.visit(node.template, frame) self.write(f", {self.name!r}).") + if node.with_context: f_name = f"make_module{self.choose_async('_async')}" self.write( @@ -995,26 +991,23 @@ class CodeGenerator(NodeVisitor): self.write("_get_default_module_async()") else: self.write("_get_default_module(context)") + + def visit_Import(self, node, frame): + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + if frame.toplevel and not node.target.startswith("_"): self.writeline(f"context.exported_vars.discard({node.target!r})") def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) - prefix = self.choose_async("await ") - self.write(f"included_template = {prefix}environment.get_template(") - self.visit(node.template, frame) - self.write(f", {self.name!r}).") - if node.with_context: - f_name = f"make_module{self.choose_async('_async')}" - self.write( - f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" - ) - elif self.environment.is_async: - self.write("_get_default_module_async()") - else: - self.write("_get_default_module(context)") - + self.write("included_template = ") + self._import_common(node, frame) var_names = [] discarded_names = [] for name in node.names: |