Skip to content

Instantly share code, notes, and snippets.

@Themis3000
Last active August 16, 2021 00:57
Show Gist options
  • Save Themis3000/be4d0567179f5955e77ebb56627e6ff1 to your computer and use it in GitHub Desktop.
Save Themis3000/be4d0567179f5955e77ebb56627e6ff1 to your computer and use it in GitHub Desktop.
An example of how a decorator can be used to limit the amount of times a generator can be iterated over
class GenLimiter:
"""A decorator used to limit the amount of iterations possible from a generator"""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
self.limit = kwargs.pop("limit", -1)
self.gen = self.func(*args, **kwargs)
return self
def __get__(self, instance, owner):
def wrapper(*args, **kwargs):
return self.__call__(instance, *args, **kwargs)
return wrapper
def __iter__(self):
return self
def __next__(self):
if self.limit == 0:
raise StopIteration()
self.limit -= 1
return next(self.gen)
@GenLimiter
def forever():
num = 0
while True:
num += 1
yield num
# Only counts to 15
for item in forever(limit=15):
print(item)
@MARIAM-O-IDEGWU
Copy link

Hello please help out. I am developing an app using tkinter python. Users are to fill the registration form and add their passport.
I want users to be able to print out a hard copy of their registration form with all their registration details including the passport when done with a button click.
Please Urgent.
My Email mariamidegwu@ymail.com
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment