[Tutor] polymorphism for file-like objects

Steven D'Aprano steve at pearwood.info
Wed Sep 1 13:23:19 CEST 2010


On Wed, 1 Sep 2010 09:24:23 am Gregory, Matthew wrote:
> 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):
[...]
> 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 expect that iterating over lines would be equivalent to:

a b c
d
a x

If you agree, then just walk the XML, and every time you see a <line> 
item, yield it.

Things get tricky if you can nest lines...

<line>a b<line>d</line>c</line>

I don't know what to expect if I see that.



> 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?

Correct.

Forget about inheritance in this case, what you care about is the 
interface. You want an object that iterates over "lines", whatever that 
happens to be.

Inheritance is useful, but it's just one way of making objects with the 
same interface.


-- 
Steven D'Aprano


More information about the Tutor mailing list