[Tutor] file-like object

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jan 14 22:15:12 CET 2005



On Fri, 14 Jan 2005, Chad Crabtree wrote:

> I have created a file-like object out of a triple quoted string.  I was
> wondering if there is a better way to implement readline than what I
> have below? It just doesn't seem like a very good way to do this.
>
> class _macroString(object):
>     def __init__(self,s):
>         self.macro=s
>         self.list=self.macro.split("\n")
>         for n,v in enumerate(self.list):
>             self.list[n]=v+'\n'
>     def readline(self,n=[-1]):
>         n[0]+=1
>         return self.list[n[0]]
>     def __str__(self):
>         return str(self.list)
>     def __len__(self):
>         return len(self.list)


Using the default parameter 'n' in the readline() method isn't safe: all
class instances will end up using the same 'n'.  You may want to put the
current line number as part of an instance's state, since two instances of
a macroString should be able to keep track of their line positions
independently.

But that being said, there's already a module in the Standard Library that
turns strings into file-like objects.  Can you use StringIO.StringIO?


Best of wishes to you!



More information about the Tutor mailing list