from prestring.python import Module from prestring.python._codeobject import CodeobjectModule m = Module() co = CodeobjectModule(m) re = co.import_("re") sys = co.import_("sys") m.sep() pattern = co.let( "pattern", re.compile( r"^(?P<label>DEBUG|INFO|WARNING|ERROR|CRITICAL):\s*(?P<message>\S+)", re.IGNORECASE, ), ) with m.for_("line", sys.stdin): matched = co.let("matched", pattern.search(co.symbol("line"))) with m.if_(f"{matched} is not None"): m.stmt("print(matched.groupdict())") print(m)
from prestring.python import Module m = Module() m.import_("math") m.sep() with m.def_('rmse', 'xs', 'ys'): m.stmt('acc = 0') m.stmt('assert len(xs) == len(ys)') with m.for_('x, y', 'zip(xs, ys)'): m.stmt('acc += (x - y) ** 2') m.return_('math.sqrt(acc / len(xs))') # m.stmt('xs = [92, 95, 110, 114, 100, 98, 93]') # m.stmt('ys = [95, 93, 100, 114, 105, 100, 96]') print(m)
from prestring.python import Module m = Module() m.import_("re") m.import_("sys") m.sep() m.stmt( "pattern = re.compile({!r}, re.IGNORECASE)", r"^(?P<label>DEBUG|INFO|WARNING|ERROR|CRITICAL):\s*(?P<message>\S+)", ) with m.for_("line", "sys.stdin"): m.stmt("m = pattern.search(line)") with m.if_("m is not None"): m.stmt("print(m.groupdict())") print(m)
from prestring.python import Module def emit_foo(m: Module, name: str, *, sep: str): with m.def_(name, "message: str"): m.return_(f"f'foo{sep}{{message}}'") return m m = Module() m = emit_foo(m, "do_foo", sep=":") with m.for_("i", "range(5)"): m.stmt("do_foo(str(i))") print(m)