Skip to content

Instantly share code, notes, and snippets.

@forivall
Last active December 19, 2015 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forivall/5914089 to your computer and use it in GitHub Desktop.
Save forivall/5914089 to your computer and use it in GitHub Desktop.
Generator Attributes
import functools
# forked from http://code.activestate.com/recipes/577057-generator-attributes/
# doesn't rely on exec or locals, works in python 2 and 3
def generator_with_attributes(fn):
@functools.wraps(fn)
def fnwrapper(*args, **kwargs):
wrapper = type(
'GeneratorWithAttributes', (object,),
{'__iter__': lambda self: gen})()
gen = fn(wrapper, *args, **kwargs)
return functools.wraps(gen, ('close', 'next', 'send', 'throw',
'gi_code', 'gi_frame', 'gi_running', '__name__'
), ())(wrapper)
return fnwrapper
@generator_with_attributes
def flagrange(self, min_, max_, flag):
'''
>>> g = flagrange(0, 10, 5)
>>> for i in g:
... print(g.flag)
False
False
False
False
False
True
True
True
True
True
'''
self.flag = False
for x in range(min_, flag):
yield x
self.flag = True
for x in range(flag, max_):
yield x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment