Feb 19
 """
     Template Dictionary module
     
     An enhancement to python's template stuff.  At present you must supply all
     parameters to instantiate a string template.  We want to be able to 
     instantiate only the paramaters that we have right now, and leave the 
     others for instantiation later.
     
     Without TDict:
     
     >>> "%(greeting)s %(person)s"%{'greeting': 'Hello', 'person': 'World'}
     'Hello World'
     >>> "%(greeting)s %(person)s"%{'greeting': 'Hello'}
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     KeyError: 'person'    
     
     This module provides class TDict (template dictionary) that, if you try 
     to read a non-existent key "keyname", returns "%(keyname)s".  Hence, it
     "passes through" any undefined names.
     
     >>> from TDict import *
     >>> a=TDict({})
     >>> a['a']='bibble'
     >>> a['a']
     'bibble'
     >>> a['b']
     '%(b)s'
     >>> "%(greeting)s %(person)s"%TDict({'greeting': 'Hello'})
     'Hello %(person)s'
     >>> tdict("%(greeting)s %(person)s",{'greeting': 'Hello'})
     'Hello %(person)s'
     
 """

 class TDict(dict):
     
     def __init__(self,d={}):
         dict.__init__(self)
         for k in d.keys():
             self[k]=d[k]
     
     def __getitem__(self, key):
         try:
             return dict.__getitem__(self, key)
         except KeyError:
             return "%%(%s)s"%key

 def tdict(template,dict):
     d=TDict(dict)
     return template%d
 

4 comments so far...

  • lordhutton Said on February 19th, 2008 at 19:04:

    shouldn’t that be ‘wibble’?

  • ianb1469 Said on February 20th, 2008 at 06:54:

    Sounds like a good way silently to goof up.

    Dear Mr %{surmane},
    Thank you for your order, it will be dispatched within ${despatch_days} days.

  • sweavo Said on February 20th, 2008 at 10:22:

    This does have application in goofing up template letters, but then, when using a pass-through technology you need to think about where you’re passing though to.

    I’m using it inside nested objects that render to strings. The catchall is easy enough - in the outermost level:

    >>> "hello"%{}
    'hello'
    >>> "hello %(surmane)s"%{}
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'surmane'
    >>>
    
  • sweavo Said on February 20th, 2008 at 10:31:

    Another way to think about this is in terms of “return types”:

    Given a template and a dict, % gives a string, whereas given a template and a TDict, it gives a template.

    when transforming textI find it very useful to think in these terms, e.g. a string prepared for a webpage looks different to a string prepared for insertion in an SQL query. I guess “encoding” is a better term than “types”

leave a reply

You must be logged in to post a comment.

 

February 2008
S M T W T F S
« Jan   Mar »
 12
3456789
10111213141516
17181920212223
242526272829  

Archives

Meta