Skip to content

Commit 4e829c0

Browse files
gh-124412: Add helpers for converting annotations to source format (#124551)
1 parent 0268b07 commit 4e829c0

File tree

5 files changed

+113
-42
lines changed

5 files changed

+113
-42
lines changed

Doc/library/annotationlib.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,27 @@ Classes
197197
Functions
198198
---------
199199

200+
.. function:: annotations_to_source(annotations)
201+
202+
Convert an annotations dict containing runtime values to a
203+
dict containing only strings. If the values are not already strings,
204+
they are converted using :func:`value_to_source`.
205+
This is meant as a helper for user-provided
206+
annotate functions that support the :attr:`~Format.SOURCE` format but
207+
do not have access to the code creating the annotations.
208+
209+
For example, this is used to implement the :attr:`~Format.SOURCE` for
210+
:class:`typing.TypedDict` classes created through the functional syntax:
211+
212+
.. doctest::
213+
214+
>>> from typing import TypedDict
215+
>>> Movie = TypedDict("movie", {"name": str, "year": int})
216+
>>> get_annotations(Movie, format=Format.SOURCE)
217+
{'name': 'str', 'year': 'int'}
218+
219+
.. versionadded:: 3.14
220+
200221
.. function:: call_annotate_function(annotate, format, *, owner=None)
201222

202223
Call the :term:`annotate function` *annotate* with the given *format*,
@@ -347,3 +368,18 @@ Functions
347368
{'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'float'>}
348369

349370
.. versionadded:: 3.14
371+
372+
.. function:: value_to_source(value)
373+
374+
Convert an arbitrary Python value to a format suitable for use by the
375+
:attr:`~Format.SOURCE` format. This calls :func:`repr` for most
376+
objects, but has special handling for some objects, such as type objects.
377+
378+
This is meant as a helper for user-provided
379+
annotate functions that support the :attr:`~Format.SOURCE` format but
380+
do not have access to the code creating the annotations. It can also
381+
be used to provide a user-friendly string representation for other
382+
objects that contain values that are commonly encountered in annotations.
383+
384+
.. versionadded:: 3.14
385+

Lib/_collections_abc.py

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -485,9 +485,10 @@ def __new__(cls, origin, args):
485485
def __repr__(self):
486486
if len(self.__args__) == 2 and _is_param_expr(self.__args__[0]):
487487
return super().__repr__()
488+
from annotationlib import value_to_source
488489
return (f'collections.abc.Callable'
489-
f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
490-
f'{_type_repr(self.__args__[-1])}]')
490+
f'[[{", ".join([value_to_source(a) for a in self.__args__[:-1]])}], '
491+
f'{value_to_source(self.__args__[-1])}]')
491492

492493
def __reduce__(self):
493494
args = self.__args__
@@ -524,23 +525,6 @@ def _is_param_expr(obj):
524525
names = ('ParamSpec', '_ConcatenateGenericAlias')
525526
return obj.__module__ == 'typing' and any(obj.__name__ == name for name in names)
526527

527-
def _type_repr(obj):
528-
"""Return the repr() of an object, special-casing types (internal helper).
529-
530-
Copied from :mod:`typing` since collections.abc
531-
shouldn't depend on that module.
532-
(Keep this roughly in sync with the typing version.)
533-
"""
534-
if isinstance(obj, type):
535-
if obj.__module__ == 'builtins':
536-
return obj.__qualname__
537-
return f'{obj.__module__}.{obj.__qualname__}'
538-
if obj is Ellipsis:
539-
return '...'
540-
if isinstance(obj, FunctionType):
541-
return obj.__name__
542-
return repr(obj)
543-
544528

545529
class Callable(metaclass=ABCMeta):
546530

Lib/annotationlib.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"call_evaluate_function",
1616
"get_annotate_function",
1717
"get_annotations",
18+
"annotations_to_source",
19+
"value_to_source",
1820
]
1921

2022

@@ -693,7 +695,7 @@ def get_annotations(
693695
return ann
694696
# But if we didn't get it, we use __annotations__ instead.
695697
ann = _get_dunder_annotations(obj)
696-
return ann
698+
return annotations_to_source(ann)
697699
case _:
698700
raise ValueError(f"Unsupported format {format!r}")
699701

@@ -762,6 +764,33 @@ def get_annotations(
762764
return return_value
763765

764766

767+
def value_to_source(value):
768+
"""Convert a Python value to a format suitable for use with the SOURCE format.
769+
770+
This is inteded as a helper for tools that support the SOURCE format but do
771+
not have access to the code that originally produced the annotations. It uses
772+
repr() for most objects.
773+
774+
"""
775+
if isinstance(value, type):
776+
if value.__module__ == "builtins":
777+
return value.__qualname__
778+
return f"{value.__module__}.{value.__qualname__}"
779+
if value is ...:
780+
return "..."
781+
if isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
782+
return value.__name__
783+
return repr(value)
784+
785+
786+
def annotations_to_source(annotations):
787+
"""Convert an annotation dict containing values to approximately the SOURCE format."""
788+
return {
789+
n: t if isinstance(t, str) else value_to_source(t)
790+
for n, t in annotations.items()
791+
}
792+
793+
765794
def _get_and_call_annotate(obj, format):
766795
annotate = get_annotate_function(obj)
767796
if annotate is not None:

Lib/test/test_annotationlib.py

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,14 @@
77
import itertools
88
import pickle
99
import unittest
10-
from annotationlib import Format, ForwardRef, get_annotations, get_annotate_function
10+
from annotationlib import (
11+
Format,
12+
ForwardRef,
13+
get_annotations,
14+
get_annotate_function,
15+
annotations_to_source,
16+
value_to_source,
17+
)
1118
from typing import Unpack
1219

1320
from test import support
@@ -25,6 +32,11 @@ def wrapper(a, b):
2532
return wrapper
2633

2734

35+
class MyClass:
36+
def __repr__(self):
37+
return "my repr"
38+
39+
2840
class TestFormat(unittest.TestCase):
2941
def test_enum(self):
3042
self.assertEqual(annotationlib.Format.VALUE.value, 1)
@@ -324,7 +336,10 @@ def test_name_lookup_without_eval(self):
324336
# namespaces without going through eval()
325337
self.assertIs(ForwardRef("int").evaluate(), int)
326338
self.assertIs(ForwardRef("int").evaluate(locals={"int": str}), str)
327-
self.assertIs(ForwardRef("int").evaluate(locals={"int": float}, globals={"int": str}), float)
339+
self.assertIs(
340+
ForwardRef("int").evaluate(locals={"int": float}, globals={"int": str}),
341+
float,
342+
)
328343
self.assertIs(ForwardRef("int").evaluate(globals={"int": str}), str)
329344
with support.swap_attr(builtins, "int", dict):
330345
self.assertIs(ForwardRef("int").evaluate(), dict)
@@ -788,9 +803,8 @@ def __annotations__(self):
788803
annotationlib.get_annotations(ha, format=Format.FORWARDREF), {"x": int}
789804
)
790805

791-
# TODO(gh-124412): This should return {'x': 'int'} instead.
792806
self.assertEqual(
793-
annotationlib.get_annotations(ha, format=Format.SOURCE), {"x": int}
807+
annotationlib.get_annotations(ha, format=Format.SOURCE), {"x": "int"}
794808
)
795809

796810
def test_raising_annotations_on_custom_object(self):
@@ -1078,6 +1092,29 @@ class C:
10781092
self.assertEqual(get_annotate_function(C)(Format.VALUE), {"a": int})
10791093

10801094

1095+
class TestToSource(unittest.TestCase):
1096+
def test_value_to_source(self):
1097+
self.assertEqual(value_to_source(int), "int")
1098+
self.assertEqual(value_to_source(MyClass), "test.test_annotationlib.MyClass")
1099+
self.assertEqual(value_to_source(len), "len")
1100+
self.assertEqual(value_to_source(value_to_source), "value_to_source")
1101+
self.assertEqual(value_to_source(times_three), "times_three")
1102+
self.assertEqual(value_to_source(...), "...")
1103+
self.assertEqual(value_to_source(None), "None")
1104+
self.assertEqual(value_to_source(1), "1")
1105+
self.assertEqual(value_to_source("1"), "'1'")
1106+
self.assertEqual(value_to_source(Format.VALUE), repr(Format.VALUE))
1107+
self.assertEqual(value_to_source(MyClass()), "my repr")
1108+
1109+
def test_annotations_to_source(self):
1110+
self.assertEqual(annotations_to_source({}), {})
1111+
self.assertEqual(annotations_to_source({"x": int}), {"x": "int"})
1112+
self.assertEqual(annotations_to_source({"x": "int"}), {"x": "int"})
1113+
self.assertEqual(
1114+
annotations_to_source({"x": int, "y": str}), {"x": "int", "y": "str"}
1115+
)
1116+
1117+
10811118
class TestAnnotationLib(unittest.TestCase):
10821119
def test__all__(self):
10831120
support.check__all__(self, annotationlib)

Lib/typing.py

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -242,21 +242,10 @@ def _type_repr(obj):
242242
typically enough to uniquely identify a type. For everything
243243
else, we fall back on repr(obj).
244244
"""
245-
# When changing this function, don't forget about
246-
# `_collections_abc._type_repr`, which does the same thing
247-
# and must be consistent with this one.
248-
if isinstance(obj, type):
249-
if obj.__module__ == 'builtins':
250-
return obj.__qualname__
251-
return f'{obj.__module__}.{obj.__qualname__}'
252-
if obj is ...:
253-
return '...'
254-
if isinstance(obj, types.FunctionType):
255-
return obj.__name__
256245
if isinstance(obj, tuple):
257246
# Special case for `repr` of types with `ParamSpec`:
258247
return '[' + ', '.join(_type_repr(t) for t in obj) + ']'
259-
return repr(obj)
248+
return annotationlib.value_to_source(obj)
260249

261250

262251
def _collect_type_parameters(args, *, enforce_default_ordering: bool = True):
@@ -2948,14 +2937,10 @@ def annotate(format):
29482937
if format in (annotationlib.Format.VALUE, annotationlib.Format.FORWARDREF):
29492938
return checked_types
29502939
else:
2951-
return _convert_to_source(types)
2940+
return annotationlib.annotations_to_source(types)
29522941
return annotate
29532942

29542943

2955-
def _convert_to_source(types):
2956-
return {n: t if isinstance(t, str) else _type_repr(t) for n, t in types.items()}
2957-
2958-
29592944
# attributes prohibited to set in NamedTuple class syntax
29602945
_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
29612946
'_fields', '_field_defaults',
@@ -3241,7 +3226,7 @@ def __annotate__(format):
32413226
for n, tp in own.items()
32423227
}
32433228
elif format == annotationlib.Format.SOURCE:
3244-
own = _convert_to_source(own_annotations)
3229+
own = annotationlib.annotations_to_source(own_annotations)
32453230
else:
32463231
own = own_checked_annotations
32473232
annos.update(own)

0 commit comments

Comments
 (0)