<jupyter_start><jupyter_text>⊕ [The world's simplest Python template engine — Makina Corpus](https://makina-corpus.com/blog/metier/2016/the-worlds-simplest-python-template-engine)<jupyter_code>'Name: {person[name]}, age: {person[age]}'.format(person={'name': 'Eric', 'age': 41})
class Song(object):
    title = 'Where is my mind'

'My favorite song is: {song.title}'.format(song=Song())
"My name is {name} and I am {age}".format(name="Eric", age=41)
"My name is %s and I am %d" % ("Eric", 41)
'{:^20}'.format('centered')
'My name is {name.upper}'.format(name='eric')
# An interesting feature of format() is the format specification: 
# instead of just inserting a field with {field}, 
# we can specify a format like this: {field:spec}.
"{:.3}".format(3.14159)
import string
class SuperFormatter(string.Formatter):

    def format_field(self, value, spec):
        if spec == 'call':
            return value()
        else:
            return super(SuperFormatter, self).format_field(value, spec)

sf=SuperFormatter()
sf.format('My name is {name.upper:call}', name="eric")        
class SuperFormatter(string.Formatter):
    """World's simplest Template engine."""

    def format_field(self, value, spec):
        if spec.startswith('repeat'):
            template = spec.partition(':')[-1]
            if type(value) is dict:
                value = value.items()
            return ''.join([template.format(item=item) for item in value])
        elif spec == 'call':
            return value()
        elif spec.startswith('if'):
            return (value and spec.partition(':')[-1]) or ''
        else:
            return super(SuperFormatter, self).format_field(value, spec)

import unittest
class TestSuperFormatterMethods(unittest.TestCase):
    """tests."""

    def test_basic(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format('a is {a}', a="A"),
            "a is A"
        )

    def test_repeat_list(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format('''Table of contents:
{chapters:repeat:Chapter {{item}}
}''', chapters=["I", "II", "III", "IV"]),
            '''Table of contents:
Chapter I
Chapter II
Chapter III
Chapter IV
'''
        )

    def test_repeat_dict(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format(
                '''Books:

{books:repeat:"{{item[1]}}" by {{item[0]}}
----
}''',
                books={
                    '<NAME>': '<NAME>',
                    '<NAME>': '<NAME>',
                }),
            '''Books:

"Notre Dame de Paris" by <NAME>
----
"<NAME>" by <NAME>
----
'''
        )

    def test_call(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format('My name is {name.upper:call}', name="eric"),
            'My name is ERIC'
        )

    def test_if_static(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format('Action: Back / Logout {manager:if:/ Delete}', manager=True),
            'Action: Back / Logout / Delete'
        )

    def test_if_with_fields(self):
        sf = SuperFormatter()
        self.assertEqual(
            sf.format('Action: Back / Logout {manager:if:/ Delete {id}}', manager=True, id=34),
            'Action: Back / Logout / Delete 34'
        )
unittest.main()<jupyter_output>E
======================================================================
ERROR: /Users/xiaofeiwu/Library/Jupyter/runtime/kernel-e6142983-7aa9-4f76-b06b-3c75e1e290cb (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '/Users/xiaofeiwu/Library/Jupyter/runtime/kernel-e6142983-7aa9-4f76-b06b-3c75e1e290cb'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)