This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: __bytes__ doesn't work for str subclasses
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.5
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 2022-04-11 14:58 by admin. This issue is now closed.

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())
>>> 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'))
>>> int(I('35'), 8)
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.

New changeset af0b95fb1c19 by Serhiy Storchaka in branch 'default':
Issue #25766: Special method __bytes__() now works in str subclasses.
Date User Action Args
2022-04-11 14:58:24adminsetgithub: 69952
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