Skip to content

Commit e3a7160

Browse files
authored
Accept falsy file-like objects in the C Unpacker (#773)
1 parent 8a88e3d commit e3a7160

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

‎msgpack/_unpacker.pyx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ cdef class Unpacker:
360360
self.ext_hook = ext_hook
361361

362362
self.file_like = file_like
363-
if file_like:
363+
if file_like is not None:
364364
self.file_like_read = file_like.read
365365
if not PyCallable_Check(self.file_like_read):
366366
raise TypeError("`file_like.read` must be a callable.")

‎test/test_sequnpack.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ def test_maxbuffersize_file():
8787
print(unpacker.unpack())
8888

8989

90+
def test_falsy_file_like():
91+
# A file-like object may define __bool__ or __len__ and be falsy
92+
# (e.g. a file wrapper without a name). Only `.read()` is required.
93+
class FalsyBytesIO(io.BytesIO):
94+
def __bool__(self):
95+
return False
96+
97+
stream = FalsyBytesIO(packb([1, 2]) + packb({"a": 3}))
98+
assert list(Unpacker(stream)) == [[1, 2], {"a": 3}]
99+
100+
unpacker = Unpacker(FalsyBytesIO(packb(1) + b"xy"))
101+
assert unpacker.unpack() == 1
102+
assert unpacker.read_bytes(2) == b"xy"
103+
104+
90105
def test_readbytes():
91106
unpacker = Unpacker(read_size=3)
92107
unpacker.feed(b"foobar")

0 commit comments

Comments
 (0)