Opened 4 years ago

Closed 4 years ago

#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


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

diff --git a/django/template/ b/django/template/
index d295d05..6dbe49f 100644
--- a/django/template/
+++ b/django/template/
@@ -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):
             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):
             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 4 years ago.

Download all attachments as: .zip

Change History (3)

Changed 4 years ago by FunkyBob

Attachment: 19846.diff added

comment:1 Changed 4 years ago by Claude Paroz

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted

comment:2 Changed 4 years ago by Claude Paroz <claude@…>

Resolution: fixed
Status: newclosed

In e5a8df06be8ce82f5ba10dca5087339704ffd0fa:

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

Thanks Curtis Maloney for the report and the patch.

Note: See TracTickets for help on using tickets.
Back to Top