Skip to content

Teach newbytes to call __bytes__ if available #275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/future/types/newbytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ def __new__(cls, *args, **kwargs):
newargs.append(errors)
value = args[0].encode(*newargs)
###
elif hasattr(args[0], '__bytes__'):
value = args[0].__bytes__()
elif isinstance(args[0], Iterable):
if len(args[0]) == 0:
# This could be an empty list or tuple. Return b'' as on Py3.
Expand Down
25 changes: 25 additions & 0 deletions tests/test_future/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,31 @@ def test_issue_171_part_b(self):
b = nativebytes(bytes(b'asdf'))
self.assertEqual(b, b'asdf')

def test_cast_to_bytes(self):
"""
Tests whether __bytes__ method is called
"""

class TestObject:
def __bytes__(self):
return b'asdf'

self.assertEqual(bytes(TestObject()), b'asdf')

def test_cast_to_bytes_iter_precedence(self):
"""
Tests that call to __bytes__ is preferred to iteration
"""

class TestObject:
def __bytes__(self):
return b'asdf'

def __iter__(self):
return iter(b'hjkl')

self.assertEqual(bytes(TestObject()), b'asdf')


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