[issue2415] bytes() should respect __bytes__

Barry A. Warsaw report at bugs.python.org
Wed Mar 19 04:04:15 CET 2008


New submission from Barry A. Warsaw <barry at python.org>:

The bytes() builtin should respect an __bytes__() converter if it exists.
E.g. instead of

>>> class Foo:
...  def __bytes__(self): return b'foo'
... 
>>> bytes(Foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Foo' object is not iterable
>>> 

bytes(Foo()) should return b'foo'

Here's one use case.  email.header.Header instances represent email headers
(naturally) that conceptually are bytes, but also have a string
representation.  Say for example, a Subject header comes across the wire in
RFC 2033 encoded utf-8.  The unicode representation would be the value
of the
header decoded according to the RFC.  The bytes representation would be the
raw bytes seen on the wire.

The most natural way to retrieve each representation would be

>>> header = msg['subject']
>>> str(header)
'some string with non-ascii'
>>> bytes(header)
b'the rfc 2033 encoded raw header value'

----------
components: Interpreter Core
messages: 64027
nosy: barry
priority: normal
severity: normal
status: open
title: bytes() should respect __bytes__
type: feature request
versions: Python 3.0

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue2415>
__________________________________


More information about the Python-bugs-list mailing list