Debian Codegraph @

Cheetah/NameMapper.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """This module supports Cheetah's optional NameMapper syntax.
3
4 Overview
5 ================================================================================
6
7 NameMapper provides a simple syntax for accessing Python data structures,
8 functions, and methods from Cheetah. It's called NameMapper because it 'maps'
9 simple 'names' in Cheetah templates to possibly more complex syntax in Python.
10
11 Its purpose is to make working with Cheetah easy for non-programmers.
12 Specifically, non-programmers using Cheetah should NOT need to be taught (a)
13 what the difference is between an object and a dictionary, (b) what functions
14 and methods are, and (c) what 'self' is. A further aim (d) is to buffer the
15 code in Cheetah templates from changes in the implementation of the Python data
16 structures behind them.
17
18 Consider this scenario:
19
20 You are building a customer information system. The designers with you want to
21 use information from your system on the client's website --AND-- they want to
22 understand the display code and so they can maintian it themselves.
23
24 You write a UI class with a 'customers' method that returns a dictionary of all
25 the customer objects. Each customer object has an 'address' method
26 that returns the a dictionary with information about the customer's address.
27 The designers want to be able to access that information.
28
29 Using PSP, the display code for the website would look something like the
30 following, assuming your servlet subclasses the class you created for managing
31 customer information:
32
33 <%= self.customer()[ID].address()['city'] %> (42 chars)
34
35 Using Cheetah's NameMapper syntax it could be any of the following:
36
37 $self.customers()[$ID].address()['city'] (39 chars)
38 --OR--
39 $customers()[$ID].address()['city']
40 --OR--
41 $customers()[$ID].address().city
42 --OR--
43 $customers()[$ID].address.city
44 --OR--
45 $customers()[$ID].address.city
46 --OR--
47 $customers[$ID].address.city (27 chars)
48
49
50 Which of these would you prefer to explain to the designers, who have no
51 programming experience? The last form is 15 characters shorter than the PSP
52 and, conceptually, is far more accessible. With PHP or ASP, the code would be
53 even messier than the PSP
54
55 This is a rather extreme example and, of course,
56 you could also just implement '$getCustomer($ID).city'
57 and obey the Law of Demeter (search Google for more on that).
58 But good object orientated design isn't the point here.
59
60 Details
61 ================================================================================
62 The parenthesized letters below correspond to the aims in the second paragraph.
63
64 DICTIONARY ACCESS (a)
65 ---------------------
66
67 NameMapper allows access to items in a dictionary
68 using the same dotted notation used to access object attributes in Python.
69 This aspect of NameMapper is known as 'Unified Dotted Notation'.
70
71 For example, with Cheetah it is possible to write::
72
73 $customers()['kerr'].address() --OR-- $customers().kerr.address()
74
75 where the second form is in NameMapper syntax.
76
77 This only works with dictionary keys that are also valid python identifiers::
78
79 regex = '[a-zA-Z_][a-zA-Z_0-9]*'
80
81
82 AUTOCALLING (b,d)
83 -----------------
84
85 NameMapper automatically detects functions and methods in Cheetah $vars
86 and calls them if the parentheses have been left off.
87
88 For example if 'a' is an object, 'b' is a method::
89
90 $a.b
91
92 is equivalent to::
93
94 $a.b()
95
96 If b returns a dictionary, then following variations are possible::
97
98 $a.b.c --OR-- $a.b().c --OR-- $a.b()['c']
99
100 where 'c' is a key in the dictionary that a.b() returns.
101
102 Further notes:
103
104 * NameMapper autocalls the function or method without any arguments. Thus
105 autocalling can only be used with functions or methods that either have no
106 arguments or have default values for all arguments.
107
108 * NameMapper only autocalls functions and methods.
109 Classes and callable object instances will not be autocalled.
110
111 * Autocalling can be disabled using Cheetah's 'useAutocalling' setting.
112
113 LEAVING OUT 'self' (c,d)
114 ------------------------
115
116 NameMapper makes it possible to access the attributes of a servlet in Cheetah
117 without needing to include 'self' in the variable names. See the NAMESPACE
118 CASCADING section below for details.
119
120 NAMESPACE CASCADING (d)
121 -----------------------
122 ...
123
124 Implementation details
125 ================================================================================
126
127 * NameMapper's search order is dictionary keys then object attributes
128
129 * NameMapper.NotFound is raised if a value can't be found for a name.
130
131 Performance and the C version
132 ================================================================================
133
134 Cheetah comes with both a C version and a Python version of NameMapper. The C
135 version is significantly faster and the exception tracebacks are much easier to
136 read. It's still slower than standard Python syntax, but you won't notice the
137 difference in realistic usage scenarios.
138
139 Cheetah uses the optimized C version (_namemapper.c) if it has
140 been compiled or falls back to the Python version if not.
141 """
142
143 from pprint import pformat
144 import inspect
145 import sys
146
147 from .compat import PY2
148 if PY2:
149 from collections import Mapping
150 else:
151 from collections.abc import Mapping
152 if sys.version_info[:2] >= (3, 13):
153 from collections.abc import MutableMapping
154
155 _INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS = False
156 _ALLOW_WRAPPING_OF_NOTFOUND_EXCEPTIONS = True
157 __all__ = ['NotFound',
158 'hasKey',
159 'valueForKey',
160 'valueForName',
161 'valueFromSearchList',
162 'valueFromFrameOrSearchList',
163 'valueFromFrame',
164 ]
165
166 if PY2 and not hasattr(inspect.imp, 'get_suffixes'):
167 # This is to fix broken behavior of the inspect module under the
168 # Google App Engine
169 setattr(inspect.imp, 'get_suffixes', lambda: [('.py', 'U', 1)])
170
171 # N.B. An attempt is made at the end of this module to import C versions of
172 # these functions. If _namemapper.c has been compiled succesfully and the
173 # import goes smoothly, the Python versions defined here will be replaced with
174 # the C versions.
175
176
177 def _raiseNotFoundException(key, namespace):
178 excString = "cannot find '%s'" % key
179 if _INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS:
180 excString += ' in the namespace %s' % pformat(namespace)
181 raise NotFound(excString)
182
183
184 def _wrapNotFoundException(exc, fullName, namespace):
185 if not _ALLOW_WRAPPING_OF_NOTFOUND_EXCEPTIONS:
186 raise
187 else:
188 excStr = exc.args[0]
189 if excStr.find('while searching') == -1: # only wrap once!
190 excStr += " while searching for '%s'" % fullName
191 if _INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS:
192 excStr += ' in the namespace %s' % pformat(namespace)
193 exc.args = (excStr,)
194 raise
195
196
197 def _isInstanceOrClass(obj):
198 if isinstance(obj, type):
199 # oldstyle
200 return True
201
202 if hasattr(obj, "__class__"):
203 # newstyle
204 if hasattr(obj, 'mro'):
205 # type/class
206 return True
207 elif (hasattr(obj, '__func__') or hasattr(obj, '__code__')
208 or hasattr(obj, '__self__')):
209 # method, func, or builtin func
210 return False
211 elif hasattr(obj, '__init__'):
212 # instance
213 return True
214 return False
215
216
217 def hasKey(obj, key):
218 """Determine if 'obj' has 'key' """
219 if isinstance(obj, Mapping) and key in obj:
220 return True
221 elif hasattr(obj, key):
222 return True
223 else:
224 return False
225
226
227 def _valueForName(obj, name, executeCallables=False):
228 nameChunks = name.split('.')
229 for key in nameChunks:
230 if isinstance(obj, Mapping) and key in obj:
231 nextObj = obj[key]
232 else:
233 try:
234 nextObj = getattr(obj, key)
235 except AttributeError:
236 _raiseNotFoundException(key, obj)
237
238 if executeCallables and callable(nextObj) and \
239 not _isInstanceOrClass(nextObj):
240 obj = nextObj()
241 else:
242 obj = nextObj
243 return obj
244
245
246 def _namespaces(callerFrame, searchList=None):
247 yield callerFrame.f_locals
248 if searchList:
249 for namespace in searchList:
250 yield namespace
251 yield callerFrame.f_globals
252 yield __builtins__
253
254
255 def hasName(obj, name):
256 # Not in the C version
257 """Determine if 'obj' has the 'name' """
258 key = name.split('.')[0]
259 if not hasKey(obj, key):
260 return False
261 try:
262 valueForName(obj, name)
263 return True
264 except NotFound:
265 return False
266
267
268 try:
269 if getattr(sys, '_cheetah_namemapper_pure', False):
270 raise ValueError # Not an error, just a way to skip ``_namemapper``
271 from ._namemapper import NotFound, valueForKey, valueForName, \
272 valueFromSearchList, valueFromFrameOrSearchList, valueFromFrame
273 C_VERSION = True
274 except Exception:
275 class NotFound(LookupError):
276 pass
277
278 def valueForKey(obj, key):
279 if isinstance(obj, Mapping) and key in obj:
280 return obj[key]
281 elif hasattr(obj, key):
282 return getattr(obj, key)
283 else:
284 _raiseNotFoundException(key, obj)
285
286 def valueForName(obj, name, executeCallables=False):
287 try:
288 return _valueForName(obj, name, executeCallables)
289 except NotFound as e:
290 _wrapNotFoundException(e, fullName=name, namespace=obj)
291
292 def valueFromSearchList(searchList, name, executeCallables=False):
293 key = name.split('.')[0]
294 for namespace in searchList:
295 if hasKey(namespace, key):
296 return _valueForName(namespace, name,
297 executeCallables=executeCallables)
298 _raiseNotFoundException(key, searchList)
299
300 def valueFromFrame(name, executeCallables=False, frame=None):
301 # @@TR consider implementing the C version the same way
302 # at the moment it provides a seperate but mirror implementation
303 # to valueFromFrameOrSearchList
304 try:
305 if not frame:
306 frame = inspect.stack()[1][0]
307 return valueFromFrameOrSearchList(
308 searchList=None, name=name,
309 executeCallables=executeCallables, frame=frame)
310 finally:
311 del frame
312
313 def valueFromFrameOrSearchList(searchList, name, executeCallables=False,
314 frame=None):
315 def __valueForName():
316 try:
317 return _valueForName(namespace, name,
318 executeCallables=executeCallables)
319 except NotFound as e:
320 _wrapNotFoundException(e, fullName=name, namespace=searchList)
321 try:
322 if not frame:
323 frame = inspect.stack()[1][0]
324 if sys.version_info[:2] >= (3, 13):
325 FrameLocalsProxy = frame.f_locals
326 if not isinstance(FrameLocalsProxy, Mapping):
327 MutableMapping.register(type(FrameLocalsProxy))
328 key = name.split('.')[0]
329 for namespace in _namespaces(frame, searchList):
330 if hasKey(namespace, key):
331 return __valueForName()
332 _raiseNotFoundException(key, searchList)
333 finally:
334 del frame
335
336 # It is possible with PyPy, Jython or Windows, for example,
337 # that _namemapper.c hasn't been compiled.
338 C_VERSION = False
339
340
341 ##################################################
342 # CLASSES
343
344
345 class Mixin:
346 """@@ document me"""
347 def valueForName(self, name):
348 return valueForName(self, name)
349
350 def valueForKey(self, key):
351 return valueForKey(self, key)
352
353 ##################################################
354 # if run from the command line ##
355
356
357 def example():
358 class A(Mixin):
359 classVar = 'classVar val'
360
361 def method(self, arg='method 1 default arg'):
362 return arg
363
364 def method2(self, arg='meth 2 default arg'):
365 return {'item1': arg}
366
367 def method3(self, arg='meth 3 default'):
368 return arg
369
370 class B(A):
371 classBvar = 'classBvar val'
372
373 a = A()
374 a.one = 'valueForOne'
375
376 def function(whichOne='default'):
377 values = {
378 'default': 'default output',
379 'one': 'output option one',
380 'two': 'output option two'
381 }
382 return values[whichOne]
383
384 a.dic = {
385 'func': function,
386 'method': a.method3,
387 'item': 'itemval',
388 'subDict': {'nestedMethod': a.method3}
389 }
390
391 b = 'this is local b' # noqa: F841 local variable assigned but never used
392
393 print(valueForKey(a.dic, 'subDict'))
394 print(valueForName(a, 'dic.item'))
395 print(valueForName(vars(), 'b'))
396 print(valueForName(__builtins__, 'dir')())
397 print(valueForName(vars(), 'a.classVar'))
398 print(valueForName(vars(), 'a.dic.func', executeCallables=True))
399 print(valueForName(vars(), 'a.method2.item1', executeCallables=True))
400
401
402 if __name__ == '__main__':
403 example()