Skip to content

Instantly share code, notes, and snippets.

@pingrunhuang
Last active July 28, 2018 16:58
Show Gist options
  • Save pingrunhuang/78b3b4c2eb5a7fa63f9f47c44a58e990 to your computer and use it in GitHub Desktop.
Save pingrunhuang/78b3b4c2eb5a7fa63f9f47c44a58e990 to your computer and use it in GitHub Desktop.
Generator and Coroutine
from contextlib import ContextDecorator
class makeparagraph(ContextDecorator):
def __enter__(self):
print('<p>')
return self
def __exit__(self, *exc):
print('</p>')
return False
@makeparagraph()
def emit_html():
print('Here is some non-HTML')
emit_html()
class Count(object):
def __init__(self, start=0, step=1, stop=10):
self.n = start
self.step = step
self.stop = stop
def __next__(self):
n = self.n
if n>self.stop:
raise StopIteration()
self.n += self.step
return n
def __iter__(self):
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment