Search code examples
pythonfilegeneratorenumerate

Iterable Derived class from file class in Python 2.6


I've a workaround, but I'm still thinking of a better way of achieve my goal. I want a class derived from base class file to access a file line by line, but getting the line number by the way. Something like a built-in enumerate feature.

I think the class should be like this:

class file2(file):
  def __init__(self, filename):
    file.__init__(self, filename)
    self._num_line = 0

  def __iter__(self):
    self._num_line = 0
    ?

to achieve this

f2 = file2('myfile.txt')
for num_line, line in f2:
  ...

My current option is to create a generator inside the child class:

    def lines(self):
        for line in self:
            self._num_line += 1
            yield (self._num_line, line)

but usage is ugly (well, not as pythonic as I would like it to be):

f2 = file2('myfile.txt')
gen = f2.lines()
for i, lin in gen:
   ...

Is there an easy way to achieve this? Thanks in advance,


Solution

  • Your __iter__ method could just have the exact same implementation as def lines(self):

    Alternatively you could do:

    def __iter__(self):
        return enumerate(file.__iter__(self))
    

    Or perhaps

    def __iter__(self):
        return enumerate(super(file, self).__iter__())
    

    Note, I shouldn't encourage this because it breaks the Liskov Substitution Principle. Your iter method now returns an iterator of tuples, not an iterator of strings. Just use enumerate on the object itself. Why use inheritance at all?