python/typeshed

`tarfile.TarFile` has several missing overloads

Open

#14.168 aperta il 27 mag 2025

Vedi su GitHub
 (2 commenti) (1 reazione) (0 assegnatari)Python (1483 fork)batch import
help wantedstubs: false negative

Metriche repository

Star
 (3436 star)
Metriche merge PR
 (Merge medio 12g 21h) (66 PR mergiate in 30 g)

Descrizione

Right now TarFile.__init__ is defined as: https://github.com/python/typeshed/blob/c7e29eccd9759411c0f46580e20727038668b320/stdlib/tarfile.pyi#L128-L132

Which is not exactly right, because there's a case when name and fileobj are both None at the same time. And this will lead to runtime errors:

>>> import tarfile
>>> tarfile.TarFile(None, fileobj=None)
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    tarfile.TarFile(None, fileobj=None)
    ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "/Users/sobolev/Desktop/cpython/Lib/tarfile.py", line 1729, in __init__
    fileobj = bltn_open(name, self._mode)
TypeError: expected str, bytes or os.PathLike object, not NoneType

Right now mypy does not raise any errors for this broken case: https://mypy-play.net/?mypy=latest&python=3.12&gist=7452d274249fafba1f8a16565d5486c6

We need either name or fileobj, they can be both None at the same time. So, we need to add overloads.

There are several other methods that needs to be updated like open and taropen, maybe others.

Guida contributor