externals: avoid importing jinja2 on startup (#14308)

Jinja2 costs a tenth to a few tenths of a second to import, so we should avoid importing it on startup.

- [x] only import jinja2 within functions
This commit is contained in:
Todd Gamblin 2019-12-28 14:43:23 -08:00 committed by GitHub
parent 2dafeaf819
commit 4d6462247e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 5 deletions

View File

@ -804,10 +804,11 @@ def write(self, overwrite=False):
# Get the template for the module
template_name = self._get_template()
import jinja2
try:
env = tengine.make_environment()
template = env.get_template(template_name)
except tengine.TemplateNotFound:
except jinja2.TemplateNotFound:
# If the template was not found raise an exception with a little
# more information
msg = 'template \'{0}\' was not found for \'{1}\''

View File

@ -5,7 +5,6 @@
import itertools
import textwrap
import jinja2
import llnl.util.lang
import six
@ -13,9 +12,6 @@
from spack.util.path import canonicalize_path
TemplateNotFound = jinja2.TemplateNotFound
class ContextMeta(type):
"""Meta class for Context. It helps reducing the boilerplate in
client code.
@ -77,6 +73,10 @@ def make_environment(dirs=None):
dirs = [canonicalize_path(d)
for d in itertools.chain(builtins, extensions)]
# avoid importing this at the top level as it's used infrequently and
# slows down startup a bit.
import jinja2
# Loader for the templates
loader = jinja2.FileSystemLoader(dirs)
# Environment of the template engine