[Tutor] polymorphism for file-like objects

Gregory, Matthew matt.gregory at oregonstate.edu
Wed Sep 1 01:24:23 CEST 2010


Hi all,

In the 2nd edition of Python Cookbook, Mark Lutz writes the intro to Chapter 2 (Files) and gives the following example of polymorphism for file like objects (adapted for brevity):

def firstword(line):
    print line.split()[0]

def scanner(fileobject, linehandler):
    for line in fileobject:
        linehandler(line)

my_file = open('foo.txt')
scanner(my_file, firstword)

from cStringIO import StringIO
my_string = StringIO('one\ntwo xxx\nthree\n')
scanner(my_string, firstword)

class MyStream(object):
    def __iter__(self):
        return iter(['a\n', 'b c d\n'])
my_stream = MyStream()
scanner(my_stream, firstword)

I understand this code and the polymorphic behavior of scanner.  But then he says you can extend this idea to other file like objects (SQL databases, XML, interactive user, etc.).  My question is how do you extend the idea when 'lines' aren't so clearly defined such as this XML snippet:

<root>
  <line>a b c</line>
  <line>d</line>
  <block>
    <line>a x</line>
  </block>
</root>

I assume you need to write a MyXMLParser that somehow defines the iteration behavior that you want such that it will work with the scanner function?  But it doesn't necessarily need to subclass file, correct?

thanks for help, matt



More information about the Tutor mailing list