Package: prestring
this package is heavily inspired bysrcgen.(todo: gentle introduction)featuresgenerating code with with-syntaxstring injection after writing stringgenerating code with with-syntaxfromprestring.pythonimportPythonModulem=PythonModule()withm.class_("Point",metaclass="InterfaceMeta"):withm.def_("__init__","self","value"):m.stmt("self.value = value")withm.def_("__str__","self"):m.return_("self.value")output is.classPoint(object,metaclass=InterfaceMeta)def__init__(self,value):self.value=valuedef__str__(self):returnself.valuestring injection after writing stringfromprestring.pythonimportPythonModulem=PythonModule()withm.def_("setup","config"):import_area=m.submodule()m.sep()forkin["a","b","c","d","e"]:import_area.stmt("from .plugins import{k}_plugin",k=k)m.stmt("config.activate({}_plugin)",k)print(m)defsetup(config):from.pluginsimport(a_plugin,b_plugin,c_plugin,d_plugin,e_plugin)config.activate(a_plugin)config.activate(b_plugin)config.activate(c_plugin)config.activate(d_plugin)config.activate(e_plugin)sub modulesprestring.outputprestring.python.transform, prestring.text.transformprestring.outputprestring.output can write multiple files.importsysfromprestring.pythonimportModulefromprestring.outputimportoutput,cleanup_all# noqadst=sys.argv[1]withoutput(root=dst)asfs:withfs.open("projects/x.txt","w")aswf:print("hello x",file=wf)print("bye x",file=wf)withfs.open("projects/y.txt","w")aswf:print("hello y",file=wf)print("bye y",file=wf)withfs.open("projects/z.py","w",opener=Module)asm:withm.def_("hello"):m.stmt("print('hello')")Above code will generate three files. if creating directory is needed, it will be created automatically.$pythonsrc/main.pydst[D]  create  dst/projects
[F]  create  dst/projects/x.txt
[F]  create  dst/projects/y.txt
[F]  create  dst/projects/z.pyOn rerun, no message is displayed. And rerun withVERBOSE=1var env to see more detailed output.$pythonsrc/main.pydst$VERBOSE=1pythonsrc/main.pydst[F]  no change       dst/projects/x.txt
[F]  no change       dst/projects/y.txt
[F]  no change       dst/projects/z.pydry-runRunning withCONSOLE=1varenv or calling withuse_console=Trueoption, doesn’t save files.$CONSOLE=1pythonsrc/main.pydst[F]  update  dst/projects/x.txt
[F]  update  dst/projects/y.txt
[F]  update  dst/projects/z.py#moreverboseoutputVERBOSE=1 CONSOLE=1 python src/00/main.py dst/00/create#dst/00/create/projects/x.txt----------------------------------------
  hello x
  bye x#dst/00/create/projects/y.txt----------------------------------------
  hello y
  bye y#dst/00/create/projects/z.py----------------------------------------
  def hello():
      print('hello')prestring.python.transform, prestring.text.transformthe Transform function means converting raw source code (or text) to prestring’s code.
And you can usepython -m prestring.python(or runningpython -m prestring.text) as a CLI command, as follows.$cathello.pydef hello(name: str, *, message: str = "hello world"):
    """
    greeting message
    """
    print(f"{name}: {message}")


if __name__ == "__main__":
    hello("foo")$python-mprestring.pythonhello.pyfrom prestring.python import PythonModule


def gen(*, m=None, indent='    '):
    m = m or PythonModule(indent=indent)

    import textwrap
    with m.def_('hello', 'name: str', '*', 'message: str =  "hello world"'):
        m.docstring(textwrap.dedent("""
        greeting message
        """).strip())
        m.stmt('print(f"{name}: {message}")')

    with m.if_('__name__ == "__main__"'):
        m.stmt('hello("foo")')
    return m


if __name__ == "__main__":
    m = gen(indent='    ')
    print(m)Of course, reversible.$python<(python-mprestring.pythonhello.py)def hello(name: str, *, message: str =  "hello world"):
    """
    greeting message
    """
    print(f"{name}: {message}")


if __name__ == "__main__":
    hello("foo")$pythonhello.pyfoo: hello world$python<(python<(python-mprestring.pythonhello.py))foo: hello worldprestring.textIf you want to prestring’s expression as first step, in other language, prestring.text is probably useful.$python-mprestring.text--tabhello.gofrom prestring.text import Module


def gen(*, m=None, indent='\t'):
    m = m or Module(indent=indent)

    m.stmt('package main')
    m.sep()
    m.stmt('import (')
    with m.scope():
        m.stmt('"fmt"')
        m.stmt('"os"')
    m.stmt(')')
    m.sep()
    m.stmt('// Hello is print Hello')
    m.stmt('func Hello(name string)  {')
    with m.scope():
        m.stmt('fmt.Printf("%s: Hello", name)')
    m.stmt('}')
    m.sep()
    m.stmt('func main()  {')
    with m.scope():
        m.stmt('var name string')
        m.stmt('if len(os.Args) > 1  {')
        with m.scope():
            m.stmt('name = os.Args[1]')
        m.stmt('} else  {')
        with m.scope():
            m.stmt('name = "foo"')
        m.stmt('}')
        m.stmt('// with block')
        m.stmt('{')
        with m.scope():
            m.stmt('Hello(name)')
        m.stmt('}')
    m.stmt('}')
    return m


if __name__ == "__main__":
    m = gen(indent='\t')
    print(m)0.9.0codeobject modulesome refactoring0.8.3, 0.8.4, 0.8.5adjustment for typing0.8.2add codeobject module, PythonModule.import_() returns symbol objectremove unused methods0.8.1prestring.python, async/await support0.8.0typing (but this is not completely strict)0.7.3In prestring.text, use tab default indent 1 (#47)0.7.2bug fix of 0.7.10.7.1“python -m prestring.python” support typed function definition0.7.0changes “python -m prestring.python.transform” to “python -m prestring.python”some logging adjustments and fix bugs (prestring.output)add prestring.text0.6.0support only python3.6+refactoring prestring.output0.5.3rollback, python’s import part output0.5.1, 0.5.2some bug fixes0.5.0add prestring.python.transform0.4.7add prestring.output.SeparatedOutputLazyKeywords is sorted0.4.3clear if empty (e.g. go-module’s  import_group)0.4.2bug fix LazyArgumentsAndKeywords0.4more lazy (python module)lazy object is cached0.3.3goname function0.3.1more lazy (go module)0.3.0go code output support