ll.xpit

Embed Python expressions in text

Home › Python software › ll.xpitText · XIST · Python

ll.xpit contains functions that make it possible to embed Python expressions and conditionals in text. For example:

from ll import xpit

text = '''
a = <?= a?>
b = <?= b?>
The sum is <?= a+b?>
<?if a>0?>a is positive<?elif a==0?>a is 0<?else?>a is negative<?endif?>
'''

print xpit.convert(text, dict(a=23, b=42))

This will print:

a = 23
b = 42
The sum is 65
a is positive

def tokenize​(string):

Tokenize the string string and split it into processing instructions and text. tokenize will generate tuples with the first item being the processing instruction target and the second being the PI data. "Text" content (i.e. anything other than PIs) will be returned as (None, data). A literal <? can be written as <?> and will be returned as text.

class UnknownTargetError​(exceptions.ValueError):

Exception that is raised when an unknown PI target (i.e. anything except =, if, elif, else, endif) is encountered.

def __init__​(self, target):

def __str__​(self):

def convert​(string, globals=None, locals=None):

Convert string using globals and locals as the global and local namespace.

All processing instructions in string with the target = (e.g. <?=23+42?>) will be evaluated with globals as the global and locals as the local namespace. Plain text will be passed through literally. Other allowed PI targets are if, else, elif and endif. These PIs implement conditional output. The PI content of if and elif is evaluated as a Python expression. If it is true, everything after this PI (up to the next else, endif etc.) will be included in the output. All these PIs will have globals as the global and locals as the local namespace.

Processing instructions with other targets will raise an UnknownTargetError exception.