示例#1
0
import inspect
from yaml.constructor import Constructor
from prestring.python import Module

m = Module()
m.from_("yaml.constructor", "Constructor")
m.sep()
with m.class_("WrappedConstructor", "Constructor"):
    with m.def_("wrap", "self", "path", "name", "node", "r"):
        with m.if_("r is None"):
            m.stmt("return r")
        m.stmt('# print("@", id(r), repr(r))')
        m.stmt("mem[id(r)] = node")
        m.stmt("return r")

    seen = set()
    for cls in Constructor.mro():
        for name, attr in cls.__dict__.items():
            if name in seen:
                continue
            seen.add(name)
            if name.startswith("construct_") and callable(attr):
                sigs = inspect.signature(attr)
                m.stmt("def {}{}:", name, sigs)
                with m.scope():
                    args = []
                    for v in sigs.parameters.values():
                        if v.name == "self":
                            continue
                        if v.default is inspect._empty:
                            args.append(str(v))
示例#2
0
from prestring.python import Module
from dictknife import DictWalker
from dictknife import loading

w = DictWalker(["lines"])
d = loading.loadfile(format="json")

r = []
for _, d in w.walk(d):
    if d["language"] == "python" or d["language"] == "py":
        r.append(d["lines"])

m = Module()
m.from_("nbreversible", "code")
for lines in r:
    with m.with_("code()"):
        for line in lines:
            if line.startswith("%"):
                m.stmt("#{}", line)
            else:
                m.stmt(line.rstrip())
    m.sep()
print(m)
示例#3
0
path = pathlib.Path(spec.origin)
if path.name == "__init__.py":
    path = path.parent
d = loading.loadfile(path / ("data/sqs/2012-11-05/service-2.json"))
"""
operations:
  <name>:
    name: <>
    input: {"shapee": <>}
    output: {"shape": <>,  "resultWrapper": <>}
    errors: {}
    documentation
"""

m = Module()
m.from_("__future__").import_("annotations")
m.sep()
m.stmt("# operations")
with m.class_("SQS"):
    for name, sd in d["operations"].items():
        with m.def_(
                name,
                f"input: {sd['input']['shape']}",
                return_type=sd["output"]["shape"] if "output" in sd else None,
        ):
            m.stmt("...")
m.stmt("# shapes")
with m.class_("SQS"):
    for name, sd in d["shapes"].items():
        with m.class_(name):
            # structure, type
示例#4
0
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)