I think the following, made so that get_annotate_function is usable in metaclasses' __new__, should check for Mapping since __prepare__ can provide any mapping (see picture from PEP3115.
However, I now realize that this is a major issue since there might be a conflict between the Mapping subtype's own annotations and the annotations it contains as a mapping for another type's namespace.
Shouldn't we separate get_annotate_function into get_annotate_function and get_namespace_annotations? Or maybe add a keyword get_annotate_function(obj, *, is_namespace: bool)?
Good point! I think what I'd like to do is drop get_annotate_function completely (it's now equivalent to a simple getattr call and doesn't need to be a function) and add a new function get_annotate_from_class_namespace.
Your proposed change is a bit dubious because "mapping" at the C level means something a little different (it basically just checks for the mp_subscr slot). Not sure if that will cause practical problems but better to be safe.
However, I now realize that this is a major issue since there might be a conflict between the Mapping subtype's own annotations and the annotations it contains as a mapping for another type's namespace.
Since instances no longer have accessible annotations by default, this will only be a problem in exotic cases like a Mapping that is also an instance of type. But again, better to be safe.
Activity
fix: ns can be mapping (closes python#132426)
eliegoudout commented on Apr 12, 2025
However, I now realize that this is a major issue since there might be a conflict between the Mapping subtype's own annotations and the annotations it contains as a mapping for another type's namespace.
Shouldn't we separate get_annotate_function into get_annotate_function and get_namespace_annotations? Or maybe add a keyword get_annotate_function(obj, *, is_namespace: bool)?
picnixz commented on Apr 12, 2025
cc @JelleZijlstra
JelleZijlstra commented on Apr 13, 2025
Good point! I think what I'd like to do is drop get_annotate_function completely (it's now equivalent to a simple getattr call and doesn't need to be a function) and add a new function get_annotate_from_class_namespace.
Your proposed change is a bit dubious because "mapping" at the C level means something a little different (it basically just checks for the mp_subscr slot). Not sure if that will cause practical problems but better to be safe.
Since instances no longer have accessible annotations by default, this will only be a problem in exotic cases like a Mapping that is also an instance of type. But again, better to be safe.
pythongh-132426: Add get_annotate_from_class_namespace replacing get_…
gh-132426: Add get_annotate_from_class_namespace replacing get_annota…
JelleZijlstra commented on May 4, 2025
Fixed by #132490, thanks for the report!
Merge remote-tracking branch 'origin/main' into call-len
pythongh-132426: Add get_annotate_from_class_namespace replacing get_…