Code

#19846 closed Cleanup/optimization (fixed)

Simplify BlockContext code with defaultdict

Reported by: FunkyBob Owned by: nobody
Component: Template system Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Just a tiny cleanup that likely gives better performance... replace the manual work with a defaultdict(list):

diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py
index d295d05..6dbe49f 100644
--- a/django/template/loader_tags.py
+++ b/django/template/loader_tags.py
@@ -5,6 +5,8 @@ from django.template.loader import get_template
 from django.utils.safestring import mark_safe
 from django.utils import six
 
+from collections import defaultdict
+
 register = Library()
 
 BLOCK_CONTEXT_KEY = 'block_context'
@@ -15,19 +17,16 @@ class ExtendsError(Exception):
 class BlockContext(object):
     def __init__(self):
         # Dictionary of FIFO queues.
-        self.blocks = {}
+        self.blocks = defaultdict(list)
 
     def add_blocks(self, blocks):
         for name, block in six.iteritems(blocks):
-            if name in self.blocks:
-                self.blocks[name].insert(0, block)
-            else:
-                self.blocks[name] = [block]
+            self.blocks[name].insert(0, block)
 
     def pop(self, name):
         try:
             return self.blocks[name].pop()
-        except (IndexError, KeyError):
+        except IndexError:
             return None
 
     def push(self, name, block):
@@ -36,7 +35,7 @@ class BlockContext(object):
     def get_block(self, name):
         try:
             return self.blocks[name][-1]
-        except (IndexError, KeyError):
+        except IndexError:
             return None
 
 class BlockNode(Node):

Attachments (1)

19846.diff (1.4 KB) - added by FunkyBob 17 months ago.

Download all attachments as: .zip

Change History (3)

Changed 17 months ago by FunkyBob

comment:1 Changed 17 months ago by claudep

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:2 Changed 17 months ago by Claude Paroz <claude@…>

  • Resolution set to fixed
  • Status changed from new to closed

In e5a8df06be8ce82f5ba10dca5087339704ffd0fa:

Fixed #19846 -- Optimized a dict of lists in BlockContext class

Thanks Curtis Maloney for the report and the patch.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.