Skip to content

Commit 2c10832

Browse files
gh-119180: Rename SOURCE format to STRING (#124620)
1 parent a4d1fdf commit 2c10832

File tree

11 files changed

+154
-169
lines changed

11 files changed

+154
-169
lines changed

Doc/library/annotationlib.rst

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ This module supports retrieving annotations in three main formats
3232
for annotations that cannot be resolved, allowing you to inspect the
3333
annotations without evaluating them. This is useful when you need to
3434
work with annotations that may contain unresolved forward references.
35-
* :attr:`~Format.SOURCE` returns the annotations as a string, similar
35+
* :attr:`~Format.STRING` returns the annotations as a string, similar
3636
to how it would appear in the source file. This is useful for documentation
3737
generators that want to display annotations in a readable way.
3838

@@ -135,7 +135,7 @@ Classes
135135
values. Real objects may contain references to, :class:`ForwardRef`
136136
proxy objects.
137137

138-
.. attribute:: SOURCE
138+
.. attribute:: STRING
139139
:value: 3
140140

141141
Values are the text string of the annotation as it appears in the
@@ -197,23 +197,23 @@ Classes
197197
Functions
198198
---------
199199

200-
.. function:: annotations_to_source(annotations)
200+
.. function:: annotations_to_string(annotations)
201201

202202
Convert an annotations dict containing runtime values to a
203203
dict containing only strings. If the values are not already strings,
204-
they are converted using :func:`value_to_source`.
204+
they are converted using :func:`value_to_string`.
205205
This is meant as a helper for user-provided
206-
annotate functions that support the :attr:`~Format.SOURCE` format but
206+
annotate functions that support the :attr:`~Format.STRING` format but
207207
do not have access to the code creating the annotations.
208208

209-
For example, this is used to implement the :attr:`~Format.SOURCE` for
209+
For example, this is used to implement the :attr:`~Format.STRING` for
210210
:class:`typing.TypedDict` classes created through the functional syntax:
211211

212212
.. doctest::
213213

214214
>>> from typing import TypedDict
215215
>>> Movie = TypedDict("movie", {"name": str, "year": int})
216-
>>> get_annotations(Movie, format=Format.SOURCE)
216+
>>> get_annotations(Movie, format=Format.STRING)
217217
{'name': 'str', 'year': 'int'}
218218

219219
.. versionadded:: 3.14
@@ -282,7 +282,7 @@ Functions
282282
NameError: name 'undefined' is not defined
283283
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
284284
ForwardRef('undefined')
285-
>>> call_evaluate_function(Alias.evaluate_value, Format.SOURCE)
285+
>>> call_evaluate_function(Alias.evaluate_value, Format.STRING)
286286
'undefined'
287287

288288
.. versionadded:: 3.14
@@ -369,14 +369,14 @@ Functions
369369

370370
.. versionadded:: 3.14
371371

372-
.. function:: value_to_source(value)
372+
.. function:: value_to_string(value)
373373

374374
Convert an arbitrary Python value to a format suitable for use by the
375-
:attr:`~Format.SOURCE` format. This calls :func:`repr` for most
375+
:attr:`~Format.STRING` format. This calls :func:`repr` for most
376376
objects, but has special handling for some objects, such as type objects.
377377

378378
This is meant as a helper for user-provided
379-
annotate functions that support the :attr:`~Format.SOURCE` format but
379+
annotate functions that support the :attr:`~Format.STRING` format but
380380
do not have access to the code creating the annotations. It can also
381381
be used to provide a user-friendly string representation for other
382382
objects that contain values that are commonly encountered in annotations.

Doc/library/typing.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3427,7 +3427,7 @@ Introspection helpers
34273427
* Replaces type hints that evaluate to :const:`!None` with
34283428
:class:`types.NoneType`.
34293429
* Supports the :attr:`~annotationlib.Format.FORWARDREF` and
3430-
:attr:`~annotationlib.Format.SOURCE` formats.
3430+
:attr:`~annotationlib.Format.STRING` formats.
34313431

34323432
*forward_ref* must be an instance of :class:`~annotationlib.ForwardRef`.
34333433
*owner*, if given, should be the object that holds the annotations that

Doc/whatsnew/3.14.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ annotations. Annotations may be evaluated in the :attr:`~annotationlib.Format.VA
9191
format (which evaluates annotations to runtime values, similar to the behavior in
9292
earlier Python versions), the :attr:`~annotationlib.Format.FORWARDREF` format
9393
(which replaces undefined names with special markers), and the
94-
:attr:`~annotationlib.Format.SOURCE` format (which returns annotations as strings).
94+
:attr:`~annotationlib.Format.STRING` format (which returns annotations as strings).
9595

9696
This example shows how these formats behave:
9797

@@ -106,7 +106,7 @@ This example shows how these formats behave:
106106
NameError: name 'Undefined' is not defined
107107
>>> get_annotations(func, format=Format.FORWARDREF)
108108
{'arg': ForwardRef('Undefined')}
109-
>>> get_annotations(func, format=Format.SOURCE)
109+
>>> get_annotations(func, format=Format.STRING)
110110
{'arg': 'Undefined'}
111111

112112
Implications for annotated code

Lib/_collections_abc.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -485,10 +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
488+
from annotationlib import value_to_string
489489
return (f'collections.abc.Callable'
490-
f'[[{", ".join([value_to_source(a) for a in self.__args__[:-1]])}], '
491-
f'{value_to_source(self.__args__[-1])}]')
490+
f'[[{", ".join([value_to_string(a) for a in self.__args__[:-1]])}], '
491+
f'{value_to_string(self.__args__[-1])}]')
492492

493493
def __reduce__(self):
494494
args = self.__args__

Lib/annotationlib.py

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@
1515
"call_evaluate_function",
1616
"get_annotate_function",
1717
"get_annotations",
18-
"annotations_to_source",
19-
"value_to_source",
18+
"annotations_to_string",
19+
"value_to_string",
2020
]
2121

2222

2323
class Format(enum.IntEnum):
2424
VALUE = 1
2525
FORWARDREF = 2
26-
SOURCE = 3
26+
STRING = 3
2727

2828

2929
_Union = None
@@ -291,9 +291,21 @@ def __convert_to_ast(self, other):
291291
return other.__ast_node__
292292
elif isinstance(other, slice):
293293
return ast.Slice(
294-
lower=self.__convert_to_ast(other.start) if other.start is not None else None,
295-
upper=self.__convert_to_ast(other.stop) if other.stop is not None else None,
296-
step=self.__convert_to_ast(other.step) if other.step is not None else None,
294+
lower=(
295+
self.__convert_to_ast(other.start)
296+
if other.start is not None
297+
else None
298+
),
299+
upper=(
300+
self.__convert_to_ast(other.stop)
301+
if other.stop is not None
302+
else None
303+
),
304+
step=(
305+
self.__convert_to_ast(other.step)
306+
if other.step is not None
307+
else None
308+
),
297309
)
298310
else:
299311
return ast.Constant(value=other)
@@ -469,7 +481,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
469481
can be called with any of the format arguments in the Format enum, but
470482
compiler-generated __annotate__ functions only support the VALUE format.
471483
This function provides additional functionality to call __annotate__
472-
functions with the FORWARDREF and SOURCE formats.
484+
functions with the FORWARDREF and STRING formats.
473485
474486
*annotate* must be an __annotate__ function, which takes a single argument
475487
and returns a dict of annotations.
@@ -487,8 +499,8 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
487499
return annotate(format)
488500
except NotImplementedError:
489501
pass
490-
if format == Format.SOURCE:
491-
# SOURCE is implemented by calling the annotate function in a special
502+
if format == Format.STRING:
503+
# STRING is implemented by calling the annotate function in a special
492504
# environment where every name lookup results in an instance of _Stringifier.
493505
# _Stringifier supports every dunder operation and returns a new _Stringifier.
494506
# At the end, we get a dictionary that mostly contains _Stringifier objects (or
@@ -524,9 +536,9 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
524536
for key, val in annos.items()
525537
}
526538
elif format == Format.FORWARDREF:
527-
# FORWARDREF is implemented similarly to SOURCE, but there are two changes,
539+
# FORWARDREF is implemented similarly to STRING, but there are two changes,
528540
# at the beginning and the end of the process.
529-
# First, while SOURCE uses an empty dictionary as the namespace, so that all
541+
# First, while STRING uses an empty dictionary as the namespace, so that all
530542
# name lookups result in _Stringifier objects, FORWARDREF uses the globals
531543
# and builtins, so that defined names map to their real values.
532544
# Second, instead of returning strings, we want to return either real values
@@ -688,14 +700,14 @@ def get_annotations(
688700
# __annotations__ threw NameError and there is no __annotate__. In that case,
689701
# we fall back to trying __annotations__ again.
690702
return dict(_get_dunder_annotations(obj))
691-
case Format.SOURCE:
692-
# For SOURCE, we try to call __annotate__
703+
case Format.STRING:
704+
# For STRING, we try to call __annotate__
693705
ann = _get_and_call_annotate(obj, format)
694706
if ann is not None:
695707
return ann
696708
# But if we didn't get it, we use __annotations__ instead.
697709
ann = _get_dunder_annotations(obj)
698-
return annotations_to_source(ann)
710+
return annotations_to_string(ann)
699711
case _:
700712
raise ValueError(f"Unsupported format {format!r}")
701713

@@ -764,10 +776,10 @@ def get_annotations(
764776
return return_value
765777

766778

767-
def value_to_source(value):
768-
"""Convert a Python value to a format suitable for use with the SOURCE format.
779+
def value_to_string(value):
780+
"""Convert a Python value to a format suitable for use with the STRING format.
769781
770-
This is inteded as a helper for tools that support the SOURCE format but do
782+
This is inteded as a helper for tools that support the STRING format but do
771783
not have access to the code that originally produced the annotations. It uses
772784
repr() for most objects.
773785
@@ -783,10 +795,10 @@ def value_to_source(value):
783795
return repr(value)
784796

785797

786-
def annotations_to_source(annotations):
787-
"""Convert an annotation dict containing values to approximately the SOURCE format."""
798+
def annotations_to_string(annotations):
799+
"""Convert an annotation dict containing values to approximately the STRING format."""
788800
return {
789-
n: t if isinstance(t, str) else value_to_source(t)
801+
n: t if isinstance(t, str) else value_to_string(t)
790802
for n, t in annotations.items()
791803
}
792804

0 commit comments

Comments
 (0)