Skip to content

TypeAliasType can leak memory if name is a str subclass #140000

Closed

Description

@JelleZijlstra

Bug report

Bug description:

TypeAliasType's traverse implementation does not visit its name. This means that we can leak memory if name is passed an instance of a mutable str subclass.

from typing import TypeAliasType
import weakref
import gc

class S(str):
    pass

def still_alive(ref):
    obj = ref()
    if not isinstance(obj, S):
        return False
    T = obj.T
    if not isinstance(T, TypeAliasType):
        return False
    return T

name = S("name")
T = TypeAliasType(name, int)
name.T = T
ref = weakref.ref(name)
assert still_alive(ref)
del name
del T
gc.collect()
gc.collect()
assert still_alive(ref)

del ref().T
assert not still_alive(ref)

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. JelleZijlstra commented on Oct 12, 2025

    @JelleZijlstra
    MemberAuthor

    This also affects TypeVar, TypeVarTuple, and ParamSpec.

  2. efimov-mikhail commented on Oct 12, 2025

    @efimov-mikhail
    Member

    Leak for all 4 types is confirmed on main, 3.14 and 3.13 branches. PR with fix is submitted.

  3. added a commit that references this issue on Oct 13, 2025
  4. added a commit that references this issue on Oct 13, 2025
  5. added 2 commits that reference this issue on Oct 13, 2025
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)topic-typingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions