8000 newbytes: accept empty sequences like [] and return newbytes(b'') · shawnp/python-future@45c97da · GitHub
[go: up one dir, main page]

Skip to content

Commit 45c97da

Browse files
committed
newbytes: accept empty sequences like [] and return newbytes(b'')
- Also add a test that would have failed before
1 parent f52d28a commit 45c97da

File tree

2 files changed

+29
-10
lines changed

2 files changed

+29
-10
lines changed

future/builtins/types/newbytes.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,18 @@ def __new__(cls, *args, **kwargs):
8686
###
8787
elif isinstance(args[0], Iterable):
8888
if len(args[0]) == 0:
89-
# What is this?
90-
raise ValueError('unknown argument type')
91-
# Was: elif len(args[0]) > 0 and isinstance(args[0][0], Integral):
92-
# # It's a list of integers
93-
# But then we can't index into e.g. frozensets. Try to proceed anyway.
94-
try:
95-
values = [chr(x) for x in args[0]]
96-
value = b''.join(values)
97-
except:
98-
raise ValueError('bytes must be in range(0, 256)')
89+
# This could be an empty list or tuple. Return b'' as on Py3.
90+
value = b''
91+
else:
92+
# Was: elif len(args[0])>0 and isinstance(args[0][0], Integral):
93+
# # It's a list of integers
94+
# But then we can't index into e.g. frozensets. Try to proceed
95+
# anyway.
96+
try:
97+
values = [chr(x) for x in args[0]]
98+
value = b''.join(values)
99+
except:
100+
raise ValueError('bytes must be in range(0, 256)')
99101
elif isinstance(args[0], Integral):
100102
if args[0] < 0:
101103
raise ValueError('negative count')

future/tests/test_bytes.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,23 @@ def test_bytes_hasattr_encode(self):
472472
self.assertFalse(hasattr(b, 'encode'))
473473
self.assertTrue(hasattr(b, 'decode'))
474474

475+
def test_quote_from_bytes(self):
476+
"""
477+
This test was failing in the backported urllib.parse module in quote_from_bytes
478+
"""
479+
empty = bytes([])
480+
self.assertEqual(empty, b'')
481+
self.assertTrue(type(empty), bytes)
482+
483+
empty2 = bytes(())
484+
self.assertEqual(empty2, b'')
485+
self.assertTrue(type(empty2), bytes)
486+
487+
safe = bytes(u'Philosopher guy: 孔子. More text here.'.encode('utf-8'))
488+
safe = bytes([c for c in safe if c < 128])
489+
self.assertEqual(safe, b'Philosopher guy: . More text here.')
490+
self.assertTrue(type(safe), bytes)
491+
475492

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

0 commit comments

Comments
 (0)
0