You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
PEP 649: class __annotate__ is shadowed by compiler-generated one #133037
I'm playing around with PEP 649, PEP 749 annotations and I found this surprising behaviour:
classC:
x: strdef__annotate__(format):
ifformat!=1:
raiseNotImplementedError()
return {'x': int}
assertC.__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.
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.
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.)
Activity
sobolevn commentedon Apr 27, 2025
See related #122285
JelleZijlstra commentedon Apr 27, 2025
This behavior is pretty inconsistent for other attributes set in the class namespace:
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.JelleZijlstra commentedon Apr 28, 2025
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.)pythongh-133037: Add test for shadowing __annotate__
gh-133037: Add test for shadowing __annotate__ (#133084)
pythongh-133037: Add test for shadowing __annotate__ (python#133084)