Skip to content

Instantly share code, notes, and snippets.

@skonik
Created September 10, 2019 18:50
Show Gist options
  • Save skonik/df669f8eeab3ff5437f87ff6f79f14a2 to your computer and use it in GitHub Desktop.
Save skonik/df669f8eeab3ff5437f87ff6f79f14a2 to your computer and use it in GitHub Desktop.
Python iterator example
import uuid
# list is iterable
names = ['Elon', 'Guido', 'Bjern']
for name in names:
print(name)
# Elon
# Guido
# Bjern
class UUIDIterator:
"""
Iterator for generating UUID.
"""
def __init__(self, limit):
self._limit = limit
self._index = 0
def __next__(self):
if self._index < self._limit:
self._index += 1
return uuid.uuid1()
raise StopIteration
class UUIDRange:
"""
Iterable object that uses Iterator.
"""
def __init__(self, count=1):
self.count = count
def __iter__(self):
"""
Return iterator object.
:return: iterator-object (UUIDIterator)
"""
return UUIDIterator(self.count)
for uuid_ in UUIDRange(3):
print(uuid_)
# 67e56182-d3fb-11e9-bca0-701ce791b04a
# 67e56402-d3fb-11e9-bca0-701ce791b04a
# 67e564e8-d3fb-11e9-bca0-701ce791b04a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment