From 2d2fbc3a70e4c3c38f0f78869dacd5588aa6a3bd Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Tue, 22 Sep 2020 08:53:17 +0100 Subject: [PATCH] Made jinja2 import lazy in django.forms. Benchmarking shows that about 22% of the startup time for a simple django project was spent importing jinja2, which the project doesn't use. It's reasonable to make this import lazy. This will only affect projects where jinja2 is installed but not used, but given the prevalence of jinja2 that's likely to be many environments (e.g. if Ansible is installed, or the global Python install is used). --- django/forms/renderers.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/django/forms/renderers.py b/django/forms/renderers.py index 19fab493cf..dcf3d92302 100644 --- a/django/forms/renderers.py +++ b/django/forms/renderers.py @@ -7,12 +7,6 @@ from django.template.loader import get_template from django.utils.functional import cached_property from django.utils.module_loading import import_string -try: - from django.template.backends.jinja2 import Jinja2 -except ImportError: - def Jinja2(params): - raise ImportError("jinja2 isn't installed") - ROOT = Path(__file__).parent @@ -58,7 +52,10 @@ class Jinja2(EngineMixin, BaseRenderer): Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ - backend = Jinja2 + @cached_property + def backend(self): + from django.template.backends.jinja2 import Jinja2 + return Jinja2 class TemplatesSetting(BaseRenderer):