Skip to content
Closed
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
5 changes: 5 additions & 0 deletions Lib/bz2.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ def __init__(self, filename, mode="r", *, compresslevel=9):
else:
self._pos = 0

if not isinstance(filename, (str, bytes)):
self.name = ''
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be some recognizable sentinel (<stream> or something better) rather than empty string?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seemed the easiest way of doing it without complicating the logic and the tests. Also, I couldn't find a uniform way of dealing with a lack of "name" for BytesIO() objects in other libraries, so I did not want to introduce anything "new and specific".
Do you have an example (or an idea) of a sentinel use that would fit here? In that case, we could do a similar change for gzip, bz2, lzma, ... libraries to have a bit more standardized way of dealing with this situation when we have BytesIO() objects.

else:
self.name = os.fspath(filename)

def close(self):
"""Flush and close the file.

Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_bz2.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,27 @@ def testBadArgs(self):
# compresslevel is keyword-only
self.assertRaises(TypeError, BZ2File, os.devnull, "r", 3)

def testNameFile(self):
self.createTempFile()
with BZ2File(self.filename) as bz2f:
self.assertTrue(hasattr(bz2f, 'name'))
self.assertTrue(bz2f.name == self.filename)

def testNameBytesIO(self):
bz2f = BZ2File(BytesIO(self.DATA))
try:
self.assertTrue(hasattr(bz2f, 'name'))
self.assertTrue(bz2f.name == '')
finally:
bz2f.close()

bz2f = BZ2File(BytesIO(), "w")
try:
self.assertTrue(hasattr(bz2f, 'name'))
self.assertTrue(bz2f.name == '')
finally:
bz2f.close()

def testRead(self):
self.createTempFile()
with BZ2File(self.filename) as bz2f:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added name attribute for BZ2File (where appropriate and possible).