Skip to content

Reference leak in OSError when setting attributes before super().__init__ #150988

Closed

Description

@lgeiger

Bug report

Bug description:

If an OSError subclass sets attributes on self prior to calling OSError.__init__ (or if __init__ is invoked multiple times) references are leaked. If OSError.__init__ is called before setting attributes no references are leaked.

import sys, gc

class LeakingOSError(OSError):
    def __init__(self, code, message, filename, filename2):
        self.strerror = message
        self.filename = filename
        self.filename2 = filename2
        super().__init__(code, message, filename, None, filename2)

msg = "some error message"
filename = "some filename"
filename2 = "some filename 2"
refcount_msg = sys.getrefcount(msg)
refcount_filename = sys.getrefcount(filename)
refcount_filename2 = sys.getrefcount(filename2)

for _ in range(5):
    try:
        raise LeakingOSError(1, msg, filename, filename2)
    except OSError:
        pass

gc.collect()

print(f"msg refcount changed: expected {refcount_msg}, got {sys.getrefcount(msg)}")
print(f"filename refcount changed: expected {refcount_filename}, got {sys.getrefcount(filename)}")
print(f"filename2 refcount changed: expected {refcount_filename2}, got {sys.getrefcount(filename2)}")
msg refcount changed: expected 4, got 9
filename refcount changed: expected 4, got 9
filename2 refcount changed: expected 4, got 9

This has been discovered in PyAV-Org/PyAV#2283

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Jun 5, 2026
  2. changed the title [-]Reference leak in `OSError` when setting attributes before `super().__init_[/-] [+]Reference leak in `OSError` when setting attributes before `super().__init__`[/+] on Jun 5, 2026
  3. added a commit that references this issue on Jun 10, 2026
  4. added a commit that references this issue on Jun 10, 2026
  5. vstinner commented on Jun 10, 2026

    @vstinner
    Member

    Thanks for the bug report and the fix. It's now fixed.

  6. added 3 commits that reference this issue on Jun 10, 2026
  7. added a commit that references this issue on Jun 17, 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

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions