Best: use the StringIO or cStringIO module instead, this is exactly what it is for. If you really need len() you could maybe subclass StringIO to do what you want.

Next best: Use an iterator. Something like this (Warning! not tested!):
class _macroString(object):
    def __init__(self,s):
        self.macro=s
        self.list=[ line+'\n' for line in self.macro.split("\n") ]
        self._iter = iter(self.list)
    def readline(self):
        try:
            return self._iter.next()
        except StopIteration:
            return ''
    def __str__(self):
        return str(self.list)
    def __len__(self):
        return len(self.list)

Note that your implementation of readline will raise IndexError when there are no more lines which is not correct behaviour.

Kent

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)

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com _______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to