typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Add overloads to TarFile.__init__ to prevent both name and fileobj being None

Open enioxt opened this issue 4 months ago • 0 comments

Description

Fixes #14168

This PR adds type overloads to TarFile.__init__ to prevent the runtime TypeError that occurs when both name and fileobj are None.

Problem

Currently, the type signature allows:

tarfile.TarFile(None, fileobj=None)  # Type checker doesn't catch this

But this causes a runtime error:

TypeError: expected str, bytes or os.PathLike object, not NoneType

Solution

Added two overloads to ensure either name or fileobj must be provided:

Overload 1: name is required (non-None)

def __init__(
    self,
    name: StrOrBytesPath,  # Required, not None
    mode: Literal["r", "a", "w", "x"] = "r",
    fileobj: _Fileobj | None = None,
    ...
) -> None: ...

Overload 2: fileobj is required when name is None

def __init__(
    self,
    name: None = None,
    mode: Literal["r", "a", "w", "x"] = "r",
    *,
    fileobj: _Fileobj,  # Required via keyword-only
    ...
) -> None: ...

Changes

  • Added overloads to both Python 3.13+ and older version branches
  • Preserved existing fallback signature for edge cases
  • No behavior changes, only type safety improvements

Testing

Type checkers (mypy, pyright) will now catch:

tarfile.TarFile(None, fileobj=None)  # ❌ Error: No matching overload
tarfile.TarFile("file.tar")          # ✅ OK
tarfile.TarFile(fileobj=obj)         # ✅ OK

Sacred Code: 000.111.369.963.1618

enioxt avatar Oct 16 '25 15:10 enioxt