Skip to content

Commit 9642c74

Browse files
committed
Teach newbytes to call __bytes__ if available
Currently, the newbytes implementation ignores __bytes__ on classes and acts like python2's str.
1 parent ecf1121 commit 9642c74

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/future/types/newbytes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def __new__(cls, *args, **kwargs):
100100
newargs.append(errors)
101101
value = args[0].encode(*newargs)
102102
###
103+
elif hasattr(args[0], '__bytes__'):
104+
value = args[0].__bytes__()
103105
elif isinstance(args[0], Iterable):
104106
if len(args[0]) == 0:
105107
# This could be an empty list or tuple. Return b'' as on Py3.

tests/test_future/test_bytes.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,31 @@ def test_issue_171_part_b(self):
707707
b = nativebytes(bytes(b'asdf'))
708708
self.assertEqual(b, b'asdf')
709709

710+
def test_cast_to_bytes(self):
711+
"""
712+
Tests whether __bytes__ method is called
713+
"""
714+
715+
class TestObject:
716+
def __bytes__(self):
717+
return b'asdf'
718+
719+
self.assertEqual(bytes(TestObject()), b'asdf')
720+
721+
def test_cast_to_bytes_iter_precedence(self):
722+
"""
723+
Tests that call to __bytes__ is preferred to iteration
724+
"""
725+
726+
class TestObject:
727+
def __bytes__(self):
728+
return b'asdf'
729+
730+
def __iter__(self):
731+
return iter(b'hjkl')
732+
733+
self.assertEqual(bytes(TestObject()), b'asdf')
734+
710735

711736
if __name__ == '__main__':
712737
unittest.main()

0 commit comments

Comments
 (0)