New submission from Karthikeyan Singaravelan <tir.kar...@gmail.com>:
This came up during https://github.com/psf/requests/issues/5229 . While fileno returns True as an attribute the actual implementation uses self.raw.fileno where the AttributeError is raised at https://github.com/python/cpython/blob/96b06aefe23521b61e4e9cdd44f5d30b00c7eb95/Lib/_pyio.py#L878 (Python implementation) . I guess it should be raising UnsupportedOperation when self.raw has no fileno so that the callers only need to catch UnsupportedOperation. Something like below for fileno implementation that will give a better exception. def fileno(self): if hasattr(self.raw, 'fileno'): return self.raw.fileno() else: self._unsupported("fileno") # tarfile_fileno.py import tarfile import os for f in ["foo.txt", "foo.tar"]: try: os.unlink(f) except OSError: pass with open("foo.txt", "w") as f: f.write("foo.txt") with tarfile.open("foo.tar", "w:gz") as tarfile_obj: tarfile_obj.add(f.name) with tarfile.open("foo.tar", "r:gz") as f: member = f.extractfile("foo.txt") print(f"Has attr : {hasattr(member, 'fileno')}") print(member.fileno()) # Current exception python.exe .\tarfile_fileno.py Has attr : True Traceback (most recent call last): File ".\tarfile_fileno.py", line 18, in <module> print(member.fileno()) AttributeError: '_FileInFile' object has no attribute 'fileno' # Proposed exception (Patching tarfile to use _pyio and modifying fileno as above) python.exe .\tarfile_fileno.py Has attr : True Traceback (most recent call last): File ".\tarfile_fileno.py", line 11, in <module> print(member.fileno()) File "C:\Users\kasingar\AppData\Local\Programs\Python\Python37-32\lib\_pyio.py", line 831, in fileno self._unsupported("fileno") File "C:\Users\kasingar\AppData\Local\Programs\Python\Python37-32\lib\_pyio.py", line 320, in _unsupported (self.__class__.__name__, name)) io.UnsupportedOperation: ExFileObject.fileno() not supported ---------- components: Library (Lib) messages: 355283 nosy: lars.gustaebel, serhiy.storchaka, xtreak priority: normal severity: normal status: open title: Misleading AttributeError accessing fileno attribute in tarfile type: behavior versions: Python 3.9 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue38572> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com