#19846: Simplify BlockContext code with defaultdict
--------------------------------------+--------------------
     Reporter:  FunkyBob              |      Owner:  nobody
         Type:  Cleanup/optimization  |     Status:  new
    Component:  Template system       |    Version:  1.4
     Severity:  Normal                |   Keywords:
 Triage Stage:  Unreviewed            |  Has patch:  1
Easy pickings:  1                     |      UI/UX:  0
--------------------------------------+--------------------
 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):
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/19846>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to