1 Sep 2010 01:24
polymorphism for file-like objects
Gregory, Matthew <matt.gregory <at> oregonstate.edu>
2010-08-31 23:24:23 GMT
2010-08-31 23:24:23 GMT
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>
(Continue reading)
RSS Feed