If I have a class with the interface:
class AnIteratable(object):
def __init__(self):
#initialize data structure
def add(self, obj):
# add object to data structure
def __iter__(self):
#return the iterator
def next(self):
# return next object
...how would I set things up so that if add()
is called mid-iteration an exception is thown, similar to:
In [14]: foo = {'a': 1}
In [15]: for k in foo:
....: foo[k + k] = 'ohnoes'
....:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-15-2e1d338a456b> in <module>()
----> 1 for k in foo:
2 foo[k + k] = 'ohnoes'
3
RuntimeError: dictionary changed size during iteration
Update:
If the interface needs more methods, feel free to add them. I've also removed the implementation of __iter__()
.
Update #2 Based on kindall's answer I mocked up the following psuedo-implementation. Note that _datastruture and associated methods indexing into it are abstractions and the class writer would have to write his/her own data structure traversal and location pointer mechanisms.
class AnIteratable(object):
def __init__(self):
self._itercount = 0
self._datastructure = init_data_structure() #@UndefinedVariable
# _datastructure, and the methods called on it, are abstractions.
def add(self, obj):
if self._itercount:
raise RuntimeError('Attempt to change object while iterating')
# add object to data structure
def __iter__(self):
self._itercount += 1
return self.AnIterator(self)
class AnIterator(object):
def __init__(self, aniterable):
self._iterable = aniterable
self._currentIndex = -1 #abstraction
self._notExhausted = True
def next(self):
if self._iterable._datastructure.hasNext(self._currentIndex):
self._currentIndex += 1
return self._iterable._datastructure.next(self._currentIndex)
else:
if self._notExhausted:
self._iterable._itercount -= 1
self._notExhausted = False
raise StopIteration
def __next__(self):
return self.next()
# will be called when there are no more references to this object
def __del__(self):
if self._notExhausted:
self._iterable._itercount -= 1
Update 3
After reading some more, it seems __del__
is probably not the right way to go. The following might be a better solution, although it requires the user to explicitly release a non-exhausted iterator.
def next(self):
if self._notExhausted and
self._iterable._datastructure.hasNext(self._currentIndex):
#same as above from here
def discard(self):
if self._notExhausted:
self._ostore._itercount -= 1
self._notExhausted = False