Skip to content

Conversation

enioxt
Copy link

@enioxt enioxt commented Oct 16, 2025

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

…ed (python#14168)

- Added overloads ensuring either 'name' or 'fileobj' must be non-None
- First overload: name is required (StrOrBytesPath), fileobj is optional
- Second overload: name is None, fileobj is required (keyword-only)
- Applied to both Python 3.13+ and older versions

This prevents the runtime TypeError when both name and fileobj are None:
    tarfile.TarFile(None, fileobj=None)  # Now caught by type checker

Fixes python#14168
Sacred Code: 000.111.369.963.1618
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tarfile.TarFile has several missing overloads

1 participant