This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author xtreak
Recipients lars.gustaebel, serhiy.storchaka, xtreak
Date 2019-10-24.06:55:31
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1571900132.35.0.991486656774.issue38572@roundup.psfhosted.org>
In-reply-to
Content
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
History
Date User Action Args
2019-10-24 06:55:32xtreaksetrecipients: + xtreak, lars.gustaebel, serhiy.storchaka
2019-10-24 06:55:32xtreaksetmessageid: <1571900132.35.0.991486656774.issue38572@roundup.psfhosted.org>
2019-10-24 06:55:32xtreaklinkissue38572 messages
2019-10-24 06:55:31xtreakcreate