diff options
author | Jelle Zijlstra <jelle.zijlstra@gmail.com> | 2025-05-04 14:26:42 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-05-04 14:26:42 (GMT) |
commit | 7cb86c5defa17147c67b56c4227e74e4c5968686 (patch) | |
tree | 129c1381785bb94524f5f369bc09299d68a1e1b2 /Lib/annotationlib.py | |
parent | 5a57248b22ad3b9aafcaaadae2c304a1923daeca (diff) | |
download | cpython-7cb86c5defa17147c67b56c4227e74e4c5968686.zip cpython-7cb86c5defa17147c67b56c4227e74e4c5968686.tar.gz cpython-7cb86c5defa17147c67b56c4227e74e4c5968686.tar.bz2 |
gh-132426: Add get_annotate_from_class_namespace replacing get_annotate_function (#132490)
As noted on the issue, making get_annotate_function() support both types and
mappings is problematic because one object may be both. So let's add a new one
that works with any mapping.
This leaves get_annotate_function() not very useful, so remove it.
Diffstat (limited to 'Lib/annotationlib.py')
-rw-r--r-- | Lib/annotationlib.py | 24 |
1 files changed, 10 insertions, 14 deletions
diff --git a/Lib/annotationlib.py b/Lib/annotationlib.py index 971f636..37f51e6 100644 --- a/Lib/annotationlib.py +++ b/Lib/annotationlib.py @@ -12,7 +12,7 @@ __all__ = [ "ForwardRef", "call_annotate_function", "call_evaluate_function", - "get_annotate_function", + "get_annotate_from_class_namespace", "get_annotations", "annotations_to_string", "type_repr", @@ -619,20 +619,16 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False): raise ValueError(f"Invalid format: {format!r}") -def get_annotate_function(obj): - """Get the __annotate__ function for an object. +def get_annotate_from_class_namespace(obj): + """Retrieve the annotate function from a class namespace dictionary. - obj may be a function, class, or module, or a user-defined type with - an `__annotate__` attribute. - - Returns the __annotate__ function or None. + Return None if the namespace does not contain an annotate function. + This is useful in metaclass ``__new__`` methods to retrieve the annotate function. """ - if isinstance(obj, dict): - try: - return obj["__annotate__"] - except KeyError: - return obj.get("__annotate_func__", None) - return getattr(obj, "__annotate__", None) + try: + return obj["__annotate__"] + except KeyError: + return obj.get("__annotate_func__", None) def get_annotations( @@ -832,7 +828,7 @@ def _get_and_call_annotate(obj, format): May not return a fresh dictionary. """ - annotate = get_annotate_function(obj) + annotate = getattr(obj, "__annotate__", None) if annotate is not None: ann = call_annotate_function(annotate, format, owner=obj) if not isinstance(ann, dict): |