Skip to content

Instantly share code, notes, and snippets.

@dpiponi

dpiponi/runner.py

Created Aug 27, 2020
Embed
What would you like to do?
Are these runners?
# Python 3
import collections
Write = collections.namedtuple("Write", ["written"])
def hello_world():
yield Write("Hello, world!")
yield Write("Hello, world!")
return 1
def identity(gen):
try:
e = next(gen)
raise ValueError("Fatal Exception")
except StopIteration as r:
return r.value
def run_write(fh, gen):
try:
e = next(gen)
while True:
if isinstance(e, Write):
fh.write(e.written)
e = next(gen)
else:
e = gen.send((yield e))
except StopIteration as r:
fh.close()
return r.value
def run_accumulate_write(acc, gen):
try:
e = next(gen)
while True:
if isinstance(e, Write):
acc += e.written
e = next(gen)
else:
e = gen.send((yield e))
except StopIteration as r:
yield Write(acc)
return r.value
print(identity(
run_write(open("hello.txt", "w"), hello_world())))
# Check contents
with open("hello.txt", "r") as fh:
print(fh.read())
print(
identity(
run_write(open("hello.txt", "w"),
run_accumulate_write("", hello_world()))))
# Check contents
with open("hello.txt", "r") as fh:
print(fh.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.