Skip to content

PEP 649: class __annotate__ is shadowed by compiler-generated one #133037

Closed

Description

@luigig44

Bug report

Bug description:

I'm playing around with PEP 649, PEP 749 annotations and I found this surprising behaviour:

class C:
    x: str
    def __annotate__(format):
        if format != 1:
            raise NotImplementedError()
        return {'x': int}

assert C.__annotate__(1) == {'x': int} # This returns {'x': str} and fails

I'm not yet sure why I would write code with annotations and then also write an explicit __annotate__, but I would expect the explicit method to prevail over the compiler-generated one. If I explicitly set C.__annotate__ = some_func afterwards it works as I would expect.

Calling dis on the provided example shows both __annotate__s getting compiled, and one overwriting the other in the class.

Related to #119180.

CPython versions tested on:

3.14, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Apr 27, 2025
  2. sobolevn commented on Apr 27, 2025

    @sobolevn
    Member

    See related #122285

  3. added
    interpreter-core
    3.14
    on Apr 27, 2025
  4. JelleZijlstra commented on Apr 27, 2025

    @JelleZijlstra
    Member

    This behavior is pretty inconsistent for other attributes set in the class namespace:

    >>> class X:
    ...     __name__ = 42
    ...     __module__ = 42
    ...     __qualname__ = "42"
    ...     __firstlineno__ = 42
    ...     __static_attributes__ = 42
    ...     
    >>> X.__name__
    'X'
    >>> X.__module__
    42
    >>> X.__qualname__
    '42'
    >>> X.__firstlineno__
    42
    >>> X.__static_attributes__
    ()
    

    Still, it's probably nicer to make this work the way this issue asks for. This can be fixed with the approach in #131550 if we do the same thing in class namespaces as we already do there for modules (assign __annotate__ early in class body execution). I'd wait for that one to be merged first and then apply the same change to class bodies.

  5. JelleZijlstra commented on Apr 28, 2025

    @JelleZijlstra
    Member

    This was actually already fixed by #132345, because now the compiler-generated __annotate__ function gets stored at a different key in the class dict. I will send a PR with a test case.

    (You'll still get your name overwritten if you use the name __annotate_func__ in user code. Don't do that.)

  6. added 2 commits that reference this issue on Apr 28, 2025
  7. added a commit that references this issue on Jul 12, 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

    3.14interpreter-coretopic-typingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions