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
 

 

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

Archives

Meta