Package commons :: Module interp
[hide private]
[frames] | no frames]

Source Code for Module commons.interp

 1  # -*- mode: python; tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4; -*- 
 2  # vim:ft=python:et:sw=4:ts=4 
 3   
 4  """ 
 5  String interpolation. Example:: 
 6   
 7      language="Python" 
 8      def printmsg(): 
 9          opinion = "favorite" 
10          print interp("My $opinion language is $language.") 
11  """ 
12   
13  import re, string, sys, UserDict 
14   
15 -class Chainmap(UserDict.DictMixin):
16 """ 17 Combine multiple mappings for sequential lookup. 18 19 From 20 U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268}. 21 Modified to support object fields, e.g. C{"${a.b}"}. 22 23 @copyright: Raymond Hettinger, 24 """ 25
26 - def __init__(self, *maps):
27 self._maps = maps
28
29 - def __getitem__(self, key):
30 keys = key.split('.') 31 key = keys[ 0 ] 32 attrs = keys[ 1 : ] 33 value = None 34 has_found = False 35 for mapping in self._maps: 36 try: 37 value = mapping[ key ] 38 has_found = True 39 break 40 except KeyError: 41 pass 42 if not has_found: 43 raise KeyError(key) 44 for attr in attrs: 45 value = getattr( value, attr ) 46 return value
47
48 -class LaxTemplate(string.Template):
49 """ 50 From U{PythonPaste 51 paste.script<http://svn.pythonpaste.org/Paste/Script/trunk/paste/script/copydir.py>}. 52 This change of pattern allows for anything in braces, but only 53 identifiers outside of braces. 54 55 @copyright: Ian Bicking 56 @license: MIT 57 """ 58 59 pattern = r""" 60 \$(?: 61 (?P<escaped>\$) | # Escape sequence of two delimiters 62 (?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier 63 {(?P<braced>.*?)} | # delimiter and a braced identifier 64 (?P<invalid>) # Other ill-formed delimiter exprs 65 ) 66 """
67
68 -def interp(s, dic = None):
69 """ 70 This returns a unicode object when a substitution is made. 71 72 From 73 U{http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308}. 74 75 @copyright: Michele Simionato 76 77 @param s: The template string. 78 @type s: str 79 80 @param dic: Specifies bindings to use in addition to the calling 81 frame's locals and globals. Defaults to C{None} for no additional 82 bindings. 83 @type dic: dict 84 """ 85 caller = sys._getframe(1) 86 if dic: 87 m = Chainmap(dic, caller.f_locals, caller.f_globals) 88 else: 89 m = Chainmap(caller.f_locals, caller.f_globals) 90 return LaxTemplate(s).substitute(m)
91