Home > Mobile >  Create custom iterator with step functionality
Create custom iterator with step functionality

Time:02-15

I have a pdf in which I create page numbers for a table of content. Some topics in a pdf overlaps into multiple pages for that I need to use steps while others stay on one page.

I have created a custom iterator like this:

class IndexPageCounter:
    """
        Used to create index page counter for a table of content
    """

    def __iter__(self):
        self.num = 1
        return self

    def __next__(self, step=1):
        num = self.num
        self.num  = step
        return num

and call it like this:

obj = iter(IndexPageCounter())
print(next(obj)) # this works fine
print(next(obj, step=2) # this doesn't work
# above line gives TypeError: next() takes no keyword arguments

I tried looking it up but I don't see any example of creating a custom iterator with step.

Edit:

I can't pass the value of step in the constructor as the value of the step is not constant.

CodePudding user response:

As mentioned in a comment, the built in next() fn doesn’t have a steps kwarg. I think you can approach this problem with a generator instead though. Something like:

def next_index_page(step=1):
  last_page = 25
  index = 1 # first page is 1 
  while index <= last_page:
    yield index 
    index  = step

If you need this to be a custom iterator class, consider putting the logic for calculating step into __next__ so that you don’t need to specify step from the calling code.

CodePudding user response:

I fixed it by creating a new function get_next like this:

class IndexPageCounter:
    """
        Used to create index page counter for a table of content
    """

    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        num = self.num
        self.num  = 1
        return num

    def get_next(self, step=1):
       for _ in range(0, step):
          self.__next__()
       return self.num

and call it like this:

obj = iter(IndexPageCounter())
print(obj.get_next()) # works
print(obj.get_next(step=2)) # works too
  • Related