Skip to content

Instantly share code, notes, and snippets.

@dpiponi
Created August 27, 2020 15:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpiponi/5ee0c535c6f60bf80b11ed63c4cce974 to your computer and use it in GitHub Desktop.
Save dpiponi/5ee0c535c6f60bf80b11ed63c4cce974 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