I was trying to make my custom class iterable by defining the __iter__
and __next__
methods. However, I want it to loop over different values under different conditions. So, I am using iter() with a yield statement when the fov_list
(a list which specifies the index of subset of data to read) is available otherwise it I want it to loop through the whole data using __iter__
and __next__
until StopIteration
exception is raised. Although, I have managed to fix the issue using a different approach. I was wondering if someone would help me understand why the __next_()
method is not getting called when the conditions are True, that is, fov_list
is not available.
class MERFISH_tools():
def __init__(self):
self.fov_list = []
FOV_list_path = os.path.join(os.path.dirname(os.path.dirname(config.get("merlin_folder"))),"analysis_parameters","fov_list","fov_list.txt")
if os.path.exists(FOV_list_path):
with open(FOV_list_path) as f:
self.fov_list = [int(fov.strip() for fov in f.readlines()]
def __iter__(self):
if len(self.fov_list) == 0:
self.i = 0
return self
else:
for fov in self.fov_list:
yield fov,self[fov]
def __next__(self) -> tuple:
i = self.i
self.i +=1
if self.i > self.positions.positions.shape[0]:
raise StopIteration
return i,self[i]
I was expecting __next__
method to be called when __iter__
returns instance of the class. Does the use of yield statement affect the function of __next__
?