[Tutor] Re: Perl to Python code migration

Michael Chermside mcherm@destiny.com
Tue, 10 Sep 2002 13:12:46 -0400


Sean 'Shaleh' Perry wrote:
> I wonder how hard it would be to add something like perl's delimiter hack to 
> the file interface.
> 
> fp = open(my_file)
> fp.set_record_delimiter('(ID 1)')
> for line in fp.xreadlines():
>     .......
> 
> Which gives you the equivalent of the perl code.

Rather than adding it to the built-in "file" object, build it (along 
with appropriate buffering) into the "DelimitedFile" object you create
by subclassing file.

Isn't it nice to be able to subclass built-in objects?

-- Michael Chermside


WARNING: Untested and almost certainly incorrect psudocode follows:


class DelimitedFile( file ):
     __slots__ = (delimiter, read_chunk_size, buffer)
     def readline(self):
         while not self.buffer.contains(delimiter):
             buffer += self.read(self.read_chunk_size)
         result, self.buffer = buffer.split(delimiter, 1)
         return result
     def set_record_delimiter(self, delimiter):
         self.delimiter = delimiter