def parse_args(self, *args, **kwargs): self.history.append({"name": "parse_args", "args": args, "kwargs": kwargs}) from prestring.python import Module, LazyArgumentsAndKeywords def _make_args(history, default=""): name = history["name"] if name == "__init__": name = default kwargs = {k: repr(v) for k, v in history["kwargs"].items()} args = [repr(v) for v in history["args"]] return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})" m = Module() with m.def_("Main"): m.import_("argparse") m.stmt(f"parser = argparse.ArgumentParser{_make_args(self.history[0])}") for x in self.history[1:-1]: m.stmt(f"parser.{_make_args(x)}") m.stmt(f"args = parser.{_make_args(self.history[-1])}") m.stmt("main(**vars(args))") with m.if_("__name__ == '__main__'"): m.stmt("Main()") print(m) sys.exit(0)
def parse_args(self, *args, **kwargs): self.history.append({"name": "parse_args", "args": args, "kwargs": kwargs}) from prestring.python import Module, LazyArgumentsAndKeywords def _make_call_stmt(history, default=""): name = history["name"] if name == "__init__": name = default kwargs = {k: repr(v) for k, v in history["kwargs"].items()} args = [repr(v) for v in history["args"]] return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})" m = Module() m.sep() with m.def_("main"): m.import_("argparse") m.stmt(f"parser = argparse.ArgumentParser{_make_call_stmt(self.history[0])}") m.stmt("parser.print_usage = parser.print_help") for x in self.history[1:-1]: m.stmt(f"parser.{_make_call_stmt(x)}") m.stmt(f"args = parser.{_make_call_stmt(self.history[-1])}") m.stmt(f"{self.fn.__name__}(**vars(args))") with m.if_("__name__ == '__main__'"): m.stmt("main()") with open(inspect.getsourcefile(self.fn)) as rf: source = rf.read() rx = re.compile("(?:@([\S]+\.)?as_command.*|^.*import ascommand.*)\n", re.MULTILINE) exposed = rx.sub("", "".join(source)) print(exposed) print(m) sys.exit(0)
def parse_args(self, *args, **kwargs): self.history.append({ "name": "parse_args", "args": args, "kwargs": kwargs }) from prestring.python import Module, LazyArgumentsAndKeywords def _make_args(history, default=""): name = history["name"] if name == "__init__": name = default kwargs = {k: repr(v) for k, v in history["kwargs"].items()} args = [repr(v) for v in history["args"]] return f"{name}({LazyArgumentsAndKeywords(args, kwargs)})" m = Module() with m.def_("Main"): m.import_("argparse") m.stmt( f"parser = argparse.ArgumentParser{_make_args(self.history[0])}" ) for x in self.history[1:-1]: m.stmt(f"parser.{_make_args(x)}") m.stmt(f"args = parser.{_make_args(self.history[-1])}") m.stmt("main(**vars(args))") with m.if_("__name__ == '__main__'"): m.stmt("Main()") print(m) sys.exit(0)
def run(*, path: str, disable_docstring) -> None: d = loading.loadfile(path) m = Module() a = Accessor(d, m, disable_docstring=disable_docstring) m.import_("typing", as_="t") m.sep() m.stmt("AnyService = t.Any # TODO") m.stmt("AnyResource = t.Any # TODO") m.sep() for rname, resource in a.resources.items(): with m.class_(titleize(rname), ""): with m.method("__init__", "resource: AnyResource"): m.stmt("self.internal = resource") m.stmt("# methods") for mname, method, params in a.iterate_methods(resource): with m.method(mname, params): a.emit_docstring(method["description"]) m.stmt( f"""# {method["httpMethod"]}: {method["flatPath"]}""") m.stmt(f"""# id: {method["id"]}""") m.stmt(f"return self.internal.{mname}({params})") m.stmt("# nested resources") for srname, subresource in a.iterate_nested_resources(resource): with m.method(srname): m.stmt(f"return self.internal.{srname}({params})") # m.stmt("# nested resources") # for mname, subresource in resource.get("resources", {}).items(): # params = LParams() # for is_positional, (pname, parameter) in itertools.zip_longest(subresource.get("parameterOrder", []), subresource.get("parameters", {}).items()): # if is_positional: # params.append(pname) # TODO type: # else: # params[pname] = None # TODO type: # with m.method(mname, params): # docstring(subresource["description"]) # m.stmt(f"""# id: {subresource["id"]}""") # m.stmt(f"return self.{mname}({params})") with m.class_("Service"): with m.method("__init__", "service: AnyService"): m.stmt("self.internal = service") for rname in a.resources.keys(): with m.method(rname, return_type=titleize(rname)): m.stmt(f"return {titleize(rname)}(self.internal.{rname}())") with m.def_("build", "*args", "**kwargs", return_type="Service"): m.stmt("# TODO: use the signature of googleapiclient.discovery.build") m.submodule().from_("googleapiclient.discovery", "build") m.stmt( f"return Service(build({a.name!r}, {a.version!r}, *args, **kwargs))" ) 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 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() dataclasses = m.import_("dataclasses") m.stmt("@{}", dataclasses.dataclass) with m.class_("Person") as Person: m.stmt("name: str") m.stmt("age: int") m.stmt(Person(name="foo", age=20)) print(m)
from prestring.python import Module import matplotlib.cm as cm m = Module() # noqa m.from_('nbreversible', 'code') m.import_('pandas as pd') m.import_('numpy as np') m.import_('seaborn as sns') m.sep() m.stmt('"# [jupyter][matplotlib][python] color mapの一覧をheatmapで"') m.stmt('# %matplotlib inline') with m.with_('code()'): m.stmt('xs = np.arange(1, 10)') m.stmt('ys = np.arange(1, 10).reshape(9, 1)') m.stmt('m = xs * ys') m.stmt('df = pd.DataFrame(m)') m.stmt('df') for name in cm.cmap_d.keys(): m.stmt(f'"## {name}"') m.sep() with m.with_("code()"): m.stmt(f"sns.heatmap(df, {name!r})") m.sep() print(m)
from prestring.python import Module m = Module() re = m.import_("re") sys = m.import_("sys") m.sep() m.stmt( "pattern = {}", re.compile( r"^(?P<label>DEBUG|INFO|WARNING|ERROR|CRITICAL):\s*(?P<message>\S+)", re.IGNORECASE, ), ) 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)