Skip to content

Instantly share code, notes, and snippets.

@stantonk
Last active August 29, 2015 14:24
Show Gist options
  • Save stantonk/b040c4bd16d15d5f83a5 to your computer and use it in GitHub Desktop.
Save stantonk/b040c4bd16d15d5f83a5 to your computer and use it in GitHub Desktop.
Indefinitely cycle through some sequence in Python, e.g. for object pools.
# loop foreva-eva
def loop(sequence):
while True:
for elem in sequence:
yield elem
# example usage, imagine you have a set of things you want
# to cycle through, removing bad ones as they appear
class ObjectPoolEmptyError(Exception):
pass
class ObjectPool(object):
def __init__(self, object_sequence):
self.__valid = set(object_sequence)
self.__pool = loop(self.__valid)
def checkout_object_from_pool(self):
# obviously, you need locking of some kind...
if len(self.__valid) > 0:
return self.__pool.next()
else:
raise ObjectPoolEmptyError()
# release locking
def report_bad_object(self, bad_obj):
# obviously requires locking...
try:
self.__valid.remove(bad_obj)
except KeyError:
pass
# update pool
self.__pool = loop(self.__valid)
# release locking
if __name__ == '__main__':
ducks = ['Daffy', 'Donald', 'Rufus']
pool = ObjectPool(ducks)
for i in range(len(ducks) * 4):
duck = pool.checkout_object_from_pool()
print i, duck
if i % 3 == 2:
print 'removing %s' % duck
pool.report_bad_object(duck)
# 0 Donald
# 1 Daffy
# 2 Rufus
# removing Rufus
# 3 Donald
# 4 Daffy
# 5 Donald
# removing Donald
# 6 Daffy
# 7 Daffy
# 8 Daffy
# removing Daffy
# Traceback (most recent call last):
# File "loop.py", line 42, in <module>
# duck = pool.checkout_object_from_pool()
# File "loop.py", line 24, in checkout_object_from_pool
# raise ObjectPoolEmptyError()
# __main__.ObjectPoolEmptyError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment