[Python-ideas] duck typing for io write methods

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Jun 13 14:46:15 CEST 2013


Nick Coghlan <ncoghlan at ...> writes:

> 
> On 13 June 2013 21:30, Wolfgang Maier
> <wolfgang.maier at ...> wrote:
> > 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.
> 
> If your type is acceptable input to operator.index(), you'll get the
> "initialised array of bytes" behaviour, and the custom str handling is
> triggered off a simple isinstance() check. It's part of the
> bytes/bytearray constructor definitions.
> 
> Cheers,
> Nick.
> 
> --
> Nick Coghlan   |   ncoghlan at ...   |   Brisbane, Australia
> 

ok, that's a nice technical explanation, but is that reasonable behavior?
Shouldn't Python check first to see if the object defines __bytes__() before
defaulting to the other options?

Besides, you don't have that problem with iterables (only tested inheritance
from list). A __bytes__ method seems to take priority over the default
behaviour, which is to expect the iterable to yield integers that are then
used to initialize an array of bytes.
Wolfgang



More information about the Python-ideas mailing list