[Python-ideas] duck typing for io write methods

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Jun 13 13:30:40 CEST 2013


Wolfgang Maier <wolfgang.maier at ...> writes:

> 
> Dear all,
> currently - and referring to Python 3 - the write methods of the different
> io module objects work on bytes and str objects only. The built-in functions
> print() and bytes(), on the other hand, use an arbitrary object's __str__
> and __bytes__ methods to compute the str and bytes they should work with.
> Wouldn't it be more consistent and pythonic if the io write methods behaved
> the same way?
> Best,
> Wolfgang
> 

Actually, I just played around with the .__bytes__ method and the bytes()
built-in function a bit and ran into a very strange behavior, which I would
call a bug, but maybe there is a reason for it?
When you define your own class inheriting from object and provide it with a
__bytes__ method, everything works fine, i.e. bytes() uses the method to get
the bytestring representation.
However, if you decide to inherit from str or int, then bytes() completely
ignores the __bytes__ method and sticks to the superclass behavior instead,
i.e. requiring an encoding for str and creating a bytestring of the length
of an int.
Example:
class byteablestr (str):
    def __bytes__(self):
        return self.encode()

s = byteablestr('abcd')
bytes(s)

Traceback (most recent call last):
  File "C:/Python33/bug.py", line 6, in <module>
    bytes(s)
TypeError: string argument without an encoding

I find it very strange that you cannot override the superclass behavior,
when you can override e.g. the __str__ method in any subclass of str.
Best,
Wolfgang




More information about the Python-ideas mailing list