Skip to content

zipfile.Path: __str__ and relative_to crash with TypeError when ZipFile was opened from a file-like object #162127

Open

Description

@klnmurthi12345

Bug report

When zipfile.Path is constructed from an in-memory io.BytesIO or any file-like object (where ZipFile.filename is None), calling str(path) or path.relative_to(other) crashes with TypeError: expected str, bytes or os.PathLike object, not NoneType.

Minimal Reproducible Example:

import io
import zipfile

# Create in-memory zip
bio = io.BytesIO()
with zipfile.ZipFile(bio, 'w') as zf:
    zf.writestr('a/b/c.txt', 'hello')

# Construct zipfile.Path from file-like object
root = zipfile.Path(bio)
child = root / 'a/b/c.txt'

# 1. str(child) fails
try:
    print(str(child))
except TypeError as e:
    print("str() error:", e)

# 2. relative_to fails
try:
    print(child.relative_to(root / 'a'))
except TypeError as e:
    print("relative_to() error:", e)

Actual Output:

str() error: expected str, bytes or os.PathLike object, not NoneType
relative_to() error: expected str, bytes or os.PathLike object, not NoneType

Traceback:

  File ".../lib/python3.13/zipfile/_path/__init__.py", line 431, in relative_to
    return posixpath.relpath(str(self), str(other.joinpath(*extra)))
  File ".../lib/python3.13/zipfile/_path/__init__.py", line 434, in __str__
    return posixpath.join(self.root.filename, self.at)
  File "<frozen posixpath>", line 77, in join
TypeError: expected str, bytes or os.PathLike object, not NoneType

Expected Behavior:

  • str(path) should handle self.root.filename is None without crashing (e.g. returning self.at).
  • relative_to between two paths within the same zip archive should compute the relative path between self.at and other.at without requiring self.root.filename.

Root Cause:

In Lib/zipfile/_path/__init__.py:

    def __str__(self):
        return posixpath.join(self.root.filename, self.at)

    def relative_to(self, other, *extra):
        return posixpath.relpath(str(self), str(other.joinpath(*extra)))

When self.root is a ZipFile initialized with a stream or buffer rather than a file path, self.root.filename is None. posixpath.join(None, self.at) raises TypeError.

CPython versions tested on:

3.13, 3.14, CPython main branch

Operating systems tested on:

Linux, macOS, Windows

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions