Brian
Brian

Reputation: 3131

Behavior change of bytes from py2 to py3

I got curious after the discussion taking place on this question. It appears that the behavior of bytes() has changed in python3. In the docs for py3 it is now listed as a built-in function that behaves the same as bytearray() except for the result being immutable. It doesn't appear in the same place in py2 docs.

In digging thru the docs for a while I couldn't really find anything detailing what's changed from 2 to 3, but it looks like something definitely has. What's the difference and why was it changed?

From the linked question in the comments someone remarked with respect to py3

bytes(1) returns b'00'

but in 2.7.5

>>> bytes(1)
'1'

Upvotes: 2

Views: 265

Answers (1)

nneonneo
nneonneo

Reputation: 179402

The Python 3 bytes constructor takes an optional int parameter specifying the number of bytes to output. All bytes are initialized to 0 (\x00) with that constructor, so bytes(1) == b'\x00'.

The Python 2 bytes constructor is identical to str, and therefore just stringizes its argument:

Python 2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes is str
True

Upvotes: 4

Related Questions