I'm programming an iterator object that returns modifications of itself and I want the original object to be part of the iteration process, so it needs to be returned before being modified.
...but:
- Creating a deepcopy of the object to return is very time-consuming.
- The object have lots of attributes, so defining auxiliary variables doesn't seem an elegant solution.
yieldinside__next__will not work because it returns a different type (generator) in each iteration instead.- I could use
yieldinside__iter__to get an iterator but then I couldn't use__next__to get on-demand iterations (my object is a Turing machine, so a controlled step-by-step print of the tape would be nice).
An example of working, but inefficient, code:
from copy import deepcopy
class MyObject():
def __init__(self, n):
self.n = n
def __str__(self):
return str(self.n)
def __iter__(self):
return self
def __next__(self):
if self.n >= 10:
raise StopIteration
self_copy = deepcopy(self)
self.n += 1
return self_copy
for x in MyObject(n=7):
print(x)
Output:
7
8
9
I'm probably missing something here but I can't figure it out.