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).
This commit is contained in:
Adam Johnson 2020-09-22 08:53:17 +01:00 committed by GitHub
parent e387f191f7
commit 2d2fbc3a70
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 7 deletions

View File

@ -7,12 +7,6 @@ from django.template.loader import get_template
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.utils.module_loading import import_string 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 ROOT = Path(__file__).parent
@ -58,7 +52,10 @@ class Jinja2(EngineMixin, BaseRenderer):
Load Jinja2 templates from the built-in widget templates in Load Jinja2 templates from the built-in widget templates in
django/forms/jinja2 and from apps' 'jinja2' directory. 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): class TemplatesSetting(BaseRenderer):