Package genshi :: Package template :: Module eval :: Class Expression

Class Expression

object --+    
         |    
      Code --+
             |
            Expression

Evaluates Python expressions used in templates.

>>> data = dict(test='Foo', items=[1, 2, 3], dict={'some': 'thing'})
>>> Expression('test').evaluate(data)
'Foo'
>>> Expression('items[0]').evaluate(data)
1
>>> Expression('items[-1]').evaluate(data)
3
>>> Expression('dict["some"]').evaluate(data)
'thing'

Similar to e.g. Javascript, expressions in templates can use the dot notation for attribute access to access items in mappings:

>>> Expression('dict.some').evaluate(data)
'thing'

This also works the other way around: item access can be used to access any object attribute:

>>> class MyClass(object):
...     myattr = 'Bar'
>>> data = dict(mine=MyClass(), key='myattr')
>>> Expression('mine.myattr').evaluate(data)
'Bar'
>>> Expression('mine["myattr"]').evaluate(data)
'Bar'
>>> Expression('mine[key]').evaluate(data)
'Bar'

All of the standard Python operators are available to template expressions. Built-in functions such as len() are also available in template expressions:

>>> data = dict(items=[1, 2, 3])
>>> Expression('len(items)').evaluate(data)
3
Instance Methods
 
evaluate(self, data)
Evaluate the expression against the given data dictionary.

Inherited from Code: __eq__, __getstate__, __hash__, __init__, __ne__, __repr__, __setstate__

Inherited from object: __delattr__, __format__, __getattribute__, __new__, __reduce__, __reduce_ex__, __setattr__, __sizeof__, __str__, __subclasshook__

Class Variables
  mode = 'eval'
Properties

Inherited from Code: ast, code, source

Inherited from object: __class__

Method Details

evaluate(self, data)

 
Evaluate the expression against the given data dictionary.
Parameters:
  • data - a mapping containing the data to evaluate against
Returns:
the result of the evaluation