Skip to content

Instantly share code, notes, and snippets.

@henrytill
Forked from dpiponi/runner.py
Created November 14, 2024 08:26
Show Gist options
  • Save henrytill/1c170216c6068cd69e5fba18bb7edde4 to your computer and use it in GitHub Desktop.
Save henrytill/1c170216c6068cd69e5fba18bb7edde4 to your computer and use it in GitHub Desktop.
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