This module defines `Templates` for embedding arbitrary iterable and replaceable expressions into blocks of text, allowing for metaprogramming and automation of tasks in other languages through python, or simply filling out forms.
C:\Anaconda3\lib\site-packages\numpy\_distributor_init.py:32: UserWarning: loaded more than 1 DLL from .libs:
C:\Anaconda3\lib\site-packages\numpy\.libs\libopenblas.NOIJJG62EMASZI6NYURL6JBKM4EVBGM7.gfortran-win_amd64.dll
C:\Anaconda3\lib\site-packages\numpy\.libs\libopenblas.PYQHXLVVQ7VESDPUVUADXEVJOBGHJPAY.gfortran-win_amd64.dll
  stacklevel=1)

lst2txt[source]

lst2txt(ltxt)

Concatenate a list of text ltxt into a string separated by newlines.

class Template[source]

Template(temp, **kwargs)

Automates iteration over arbitrary Python functions embedded into blocks of text.

Class attrs:

funcs=[[`ZIP`](/sidis/templates.html#ZIP)] (list of callable) : the keyword function to map over the text it's embedded in

filler=[`fill`](/sidis/conversion.html#fill) (callable) : method of filling the text


Inputs:

`temp` (str): input string to be filled, or file name to be loaded

`kwargs` (dict): characters to be replaced and evaluated


Attrs:

`plate` (list): line-by-line filling of `temp` based on `kwargs`

`temp` (str): saved version of `temp` separated by newlines


Methods:

[`load`](/sidis/utils.html#load): loads `fname` and fills based on `kwargs`.

`out`: write/append `txt`, which defaults to filled data `str`, to `fname`.

[`fill`](/sidis/conversion.html#fill): fills the template by replacing `kwargs` and evaluating `funcs`.
t=Template('''These characters get replaced: _variable, _function

This line is then formatted: {0} ZIP _variable , _function

And this one is iterated: {0} ZIP _iter , _function''')
t.fill(_variable=2,_function="lambda i:i*10",_iter=range(2))
t
These characters get replaced: 2, lambda i:i*10
This line is then formatted: 20 
And this one is iterated: 0 
And this one is iterated: 10 

What happened? When calling t.fill, _variable was replaced with 2 everywhere it appeared in the template, similarly with _function. This includes after the custom function ZIP, where they appear as arguments.

After this substitution, ZIP formatted the text preceding it ({0}) with the result of _function(_variable), i.e, format("{0}",(lambda i:i*10)(2)).

In the next line, ZIP repeatedly formatted the text preceding it ({0}) with the result of _function(_iter), i.e, '\n'.join([format("{0}",(lambda i:i*10)(j)) for j in range(2)]).

Before we go into more detail on these functions, let's examine the template object:

t.__dict__
{'temp': 'These characters get replaced: _variable, _function\n\nThis line is then formatted: {0} ZIP _variable , _function\n\nAnd this one is iterated: {0} ZIP _iter , _function',
 'plate': ['These characters get replaced: 2, lambda i:i*10',
  'This line is then formatted: 20 ',
  'And this one is iterated: 0 ',
  'And this one is iterated: 10 '],
 '_variable': 2,
 '_function': 'lambda i:i*10',
 '_iter': range(0, 2)}

The temp attribute stores the un-formatted text handed to Template. The plate attribute stores the formatted lines as a list of strings. The object also stores any kwargs as attrs. Finally, text() attribute concatenates the formatted text into a string separated by newlines, and is used as the __repr__.

Let's see how ZIP works:

ZIP[source]

ZIP(txt, _iter, *lambdas, as_txt=False)

Loop over the iterable _iter and format txt in order of the lambdas. If _iter is an int, it is treated as range(_iter), and if it is a tuple, it is treated as np.ndindex(_iter).

ZIP('{0}',range(10),lambda i:i)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

When embedded in the Template, ZIP treats the text proceeding it as an iterable or a single-substitution, and any text after the , as a list of functions. These functions take the iterable as an argument, and format the text preceding ZIP with their evaluation on the iterable. They do not need to be lambdas - any callable will do. This makes embedding ZIP into other text documents a useful way to modularize the formatting of text, and automate code blocks in other languages which lack Python flexibility.

Other helper functions enabling this process are as follows:

replace[source]

replace(l, **kwargs)

Replace the line l in txt with any occurances of the dictionaried values.

replace('''result={0}; ZIP _myvar,lambda i:i*10''',_myvar=2)
'result={0}; ZIP 2,lambda i:i*10'

txt2lst[source]

txt2lst(txt)

Remove all newlines ` and empty strings `` from the templatetxt`.

txt=txt2lst('''var=_myvar
result={0}; ZIP _myvar,lambda i:i*10
''')
txt
['var=_myvar', 'result={0}; ZIP _myvar,lambda i:i*10']

getEvals[source]

getEvals(replaced_txt, funcs=['ZIP'])

Obtain a tuple of containing the funcs, the text they format, their arguments, and their line index in the template txt.

for i,l in enumerate(txt):
    txt[i]=replace(l,_myvar=2)
getEvals(txt,funcs=['ZIP'])
[('ZIP', ['result={0}; ', ' 2,lambda i:i*10'], 1)]

Text blocks of this kind (ZIP, follows by text to format, follows by arguments after comma) are extracted using filltxt:

filltxt[source]

filltxt(txt, funcs=['ZIP'], **kwargs)

Take a template txt, replace all kwargs via Replace, then evaluate the funcs on the surrounding text using GetEvals.

These are then packaged into the Template class, which we give another arbitrary example of here:

t=Template('''Filling out _stuff

which {0}{1} is ZIP 1, lambda t:'iterates ' , _arbitrarily

{0} ZIP range(3), lambda t: "much"

easier

since we can embed any keyword, iterable, and function anywhere.

''',_stuff='stuff',_arbitrarily="lambda t: 'arbitrarily'")
t
Filling out stuff
which iterates arbitrarily is 
much 
much 
much 
easier
since we can embed any keyword, iterable, and function anywhere.
t.fill('we can append, _too',_too='too!',append=True)
t
Filling out stuff
which iterates arbitrarily is 
much 
much 
much 
easier
since we can embed any keyword, iterable, and function anywhere.
we can append, too!

Finally, a Template will attempt to auto-load a file if the input is a filename, e.g Template('template.txt') will load the file template.txt if it exists in the current directory, and use that as the string to format.