[Python-ideas] duck typing for io write methods

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


Oscar Benjamin <oscar.j.benjamin at ...> writes:

> 
> On 13 June 2013 13:24, Nick Coghlan <ncoghlan at ...> wrote:
> > If your type is acceptable input to operator.index(), you'll get the
> > "initialised array of bytes" behaviour
> 
> I only recently discovered this. What was the rationale for that change?
> 
> $ py -2.7 -c 'print(repr(bytes(4)))'
> '4'
> 
> $ py -3.3 -c 'print(repr(bytes(4)))'
> b'\x00\x00\x00\x00'
> 
> I can't really see why anyone would want the latter behaviour (when
> you can already do b'\x00' * 4).
> 
> Oscar
> 

It's funny you mention that difference since that was how I came across my
issue. I was looking for a way to get back the Python 2.7 behaviour
bytes('1234')
'1234'
in Python3. The __bytes__ method does not offer an easy solution for this
though. I could only think of str(1234).encode(), which feels ridiculous.
Any better ways?
Wolfgang




More information about the Python-ideas mailing list