classification
Title: __bytes__ doesn't work for str subclasses
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.5
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: serhiy.storchaka Nosy List: mark.dickinson, python-dev, serhiy.storchaka, skrah
Priority: normal Keywords: patch

Created on 2015-11-29 20:26 by serhiy.storchaka, last changed 2015-12-20 17:06 by serhiy.storchaka. This issue is now closed.

Files
File name Uploaded Description Edit
str___bytes__.patch serhiy.storchaka, 2015-11-29 20:26 review
Messages (3)
msg255593 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2015-11-29 20:26
Special __bytes__ method is purposed for converting to bytes with bytes constructor (as well as __str__ and __float__ for str and float). But this doesn't work if the class is a subclass of str.

>>> class X:
...     def __bytes__(self):
...         return b'abc'
... 
>>> bytes(X())
b'abc'
>>> class Y(str):
...     def __bytes__(self):
...         return b'abc'
... 
>>> bytes(Y())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
msg256375 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2015-12-14 09:01
Other conversion special methods work in str subclass.

>>> class I(str):
...     def __int__(self):
...         return 42
... 
>>> int(I('35'))
42
>>> int(I('35'), 8)
29
msg256769 - (view) Author: Roundup Robot (python-dev) (Python triager) Date: 2015-12-20 16:04
New changeset 1e54adef4064 by Serhiy Storchaka in branch '3.5':
Issue #25766: Special method __bytes__() now works in str subclasses.
https://hg.python.org/cpython/rev/1e54adef4064

New changeset af0b95fb1c19 by Serhiy Storchaka in branch 'default':
Issue #25766: Special method __bytes__() now works in str subclasses.
https://hg.python.org/cpython/rev/af0b95fb1c19
History
Date User Action Args
2015-12-20 17:06:24serhiy.storchakasetstatus: open -> closed
resolution: fixed
stage: patch review -> resolved
2015-12-20 16:04:21python-devsetnosy: + python-dev
messages: + msg256769
2015-12-20 14:34:28serhiy.storchakasetassignee: serhiy.storchaka
versions: - Python 3.4
2015-12-14 09:01:03serhiy.storchakasetnosy: + mark.dickinson, skrah
messages: + msg256375
2015-11-29 20:26:42serhiy.storchakacreate