Source

python-jfine-new / py2 / jfine / work.py

Full commit
'''Module docstring.'''

# Future imports that work in Python 2.5 and later.
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement

# Future imports that work in Python 2.6 and later.
# from __future__ import print_function
# from __future__ import unicode_literals

# Prevent use of old-style classes.
__metaclass__ = type


# Example of a template function.  All it needs is a script.
def f(extend, script):
    locs = locals()
    for flag, fn in script:
        if False:
            pass
        elif flag == 1:
            a, b = fn(locs)
            extend((
                    'A',
                    a,
                    b,
                    'C',
                    c,
                    ))
        elif flag == 2:
            c,  = fn(locs)
            extend((
                    'a',
                    ))
        elif flag == 3:
            a, c = fn(locs)
            extend((
                    'b',
                    b,
                    ))


def indent_and_format(s):

    argv = tuple(
        ' ' * i
        for i in range(0, 20, 4)
        )
    return s.format(*argv).format

formats = dict(
    HEADER = '''\
def f(extend, script):
{1}locs = locals()
{1}for flag, fn in script:
{1}{1}if False:
{1}{1}{1}pass
''',
    IF = '{2}elif flag == {{0}}:\n',
    BEGIN = '{3}{{0}} = fn(locs)\n{3}extend((\n',
    STRING = '{4}{{0!r}},\n',
    VAR = '{4}{{0}},\n',
    END = '{4}))\n',
    )

formats = dict(
    (name, indent_and_format(s))
    for name, s in formats.iteritems()
    )

assert formats['IF'](12) == '        elif flag == 12:\n'

def doit(pairs):

    return ''.join(
        formats[key](value)
        for key, value in pairs
)


print doit((
        ('HEADER', None),
        ('IF', 1),
        ('BEGIN', 'a,b'),
        ('STRING', 'A'),
        ('VAR', 'a'),
        ('VAR', 'b'),
        ('STRING', 'C'),
        ('VAR', 'c'),
        ('END', None),
        ('IF', 2),
        ('BEGIN', 'c,'),
        ('STRING', 'a'),
        ('END', None),
        ('IF', 3),
        ('BEGIN', 'a, c'),
        ('STRING', 'b'),
        ('VAR', 'b'),
        ('END', None),
))