Skip to content

Unexpected name mangling behavior with generics #119311

Closed

Description

@gaesa

Bug report

Bug description:

Name mangling behaves inconsistently when used with generics. Here’s the code to reproduce the issue:

class __Foo(type):
    pass


class Bar[T](metaclass=__Foo):
    pass

This raises NameError: name '_Bar__Foo' is not defined. However, removing the [T] results in the error disappearing. This suggests that the name mangling behavior is inconsistent when generics are involved. This behavior seems to be a bug, as it would be expected for the name mangling to either always occur or never occur, regardless of whether generics are used.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on May 21, 2024
  2. JelleZijlstra commented on May 22, 2024

    @JelleZijlstra
    Member

    I agree this is a bug. We apply name mangling to all names that appear in the type parameter scope for the generic class (and also to all code after it, which is a separate bug: #119395). In the example, this means __Foo in the bases gets mangled to _Bar__Foo.

    We could instead not do any mangling in the type parameter scope. That would fix this bug and simplify the code. However, it would break cases like this:

    class X[__T]:
        def foo(self, x: __T): ...
    

    If we didn't do mangling in the type parameter scope, the second use of __T would get mangled, but the first one wouldn't, so the second use of __T would fail to resolve.

    Fortunately, the set of names that can appear in a type parameter scope is very limited. I think it should be possible to mangle only the type parameter names defined in the scope but nothing else. This would make both my example and the OP's example work, but it adds some complexity to the symtable.

  3. added 2 commits that reference this issue on May 23, 2024
  4. added 3 commits that reference this issue on May 28, 2024
  5. added a commit that references this issue on Jun 4, 2024
  6. added a commit that references this issue on Jul 17, 2024
  7. added a commit that references this issue on Oct 21, 2024
  8. added a commit that references this issue on Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

3.12only security fixes3.13only security fixes3.14bugs and security fixesrelease-blockertopic-typingtype-bugAn unexpected behavior, bug, or error

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions