the bytes type in python 2.7 and PEP-358

前端 未结 3 1804
囚心锁ツ
囚心锁ツ 2020-11-28 11:49

According to PEP 358, a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case.

However, my python 2.7 says otherwise

相关标签:
3条回答
  • 2020-11-28 12:19

    The bytes type was introduced in Python 3, but what's being discussed in the PEP is a mutable sequence (bytes is immutable) which was introduced in Python 2.6 under the name bytearray.

    The PEP clearly wasn't implemented as stated (and it does say that it was partially superseded by PEP 3137) but I think it's only a question of things being renamed, not features missing. In Python 2 bytes is just an alias for str to aid forward compatibility and so is a red-herring here.

    Example bytearray usage:

    >>> a = bytearray([1,2,3])
    >>> a[0] = 5
    >>> a
    bytearray(b'\x05\x02\x03')
    
    0 讨论(0)
  • 2020-11-28 12:26

    The new bytes type is 3.x only. The 2.x bytes built-in is just an alias to the str type. There is no new type called bytes in 2.x; Just a new alias and literal syntax for str.

    Here's the documentation snippet everybody loves:

    Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

    The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list.

    The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.

    0 讨论(0)
  • 2020-11-28 12:31

    bytes objects only really exist in Python 3.x. bytes is an alias for str in Python 2.7. It exists to help writing portable code between Python 2 and 3.

    0 讨论(0)
提交回复
热议问题