I am designing a custom iterator in python:
class Iterator():
def __init__(self):
return
def fit(self, n):
self.n = n
return self
def __iter__(self):
for i in range(self.n):
yield i
return
it = Iterator().fit(10)
for i in it:
print(i)
it.fit(20)
for i in it:
print(i)
It is working fine but I am wondering if it is possible that a new fit
is called before that the previous one is finished leading to strange behaviour of the class.
If yes how should I design it to make it more robust?
It is important to have some parameters passed from the fit
method.
EDIT: I will introduce an example that is similar to my original problem
The iterator
class is designed to be used by a User
class. It is important that when the evaluate
method is called all the numbers until n/k
are printed. Without any exception.
Maybe the use of a iterator.fit(n)
method solves the problem?
class Iterator():
def __init__(self, k):
self.k = k
return
def fit(self, n):
for i in range(int(n/self.k)):
yield i
return
class User():
def __init__(self, iterator):
self.iterator = iterator
return
def evaluate(self, n):
for i in self.iterator.fit(n):
print(i)
return
it = Iterator(2)
u = User(it)
u.evaluate(10) # I want to be sure that all the numbers until 9 are printed
u.evaluate(20) # I want to be sure that all the numbers until 20 are printed