[Python-3000] TextIOWrapper.write(s:str) and bytes in py3k-struni

Christian Heimes lists at cheimes.de
Tue Jul 17 03:22:13 CEST 2007


Guido van Rossum wrote:
> I came across this in your SF patch. I disagree with your desire to
> let TextIOWrapper.write() handle bytes: it should *only* be passed str
> objects. The uu test was failing because it was writing bytes to a
> text stream.
> 
> Perhaps the error should be better; though I'm not sure I want to add
> explicit type checks (as it would defeat duck typing).

Yes, duck typing is very useful but this duck doesn't quack me why it
hurts. ;) It's rather confusing at first.

What do you think about

    def write(self, s: str):
        if self.closed:
            raise ValueError("write to closed file")
        try:
            b = s.encode(self._encoding)
        except AttributeError:
            raise TypeError("str expected, got %r" % s)
        ...

    def write(self, s: str):
        if self.closed:
            raise ValueError("write to closed file")
        if not hasattr(s, 'encode')
            raise TypeError("str expected, got %r" % s)
        ...

? It explains what is going wrong.

Christian



More information about the Python-3000 mailing list