GeezerVison is showing github.com — bpo-38605: Make 'from __future__ import annotations' the default (GH-… · Maddie-Code-Collab/cpython@044a104
File treeExpand file treeCollapse file tree Open diff view settings Misc/NEWS.d/next/Core and Builtins
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: Doc/reference/compound_stmts.rst +3-7Lines changed: 3 additions & 7 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -610,13 +610,9 @@ following the parameter name. Any parameter may have an annotation, even those | 610 | 610 | ``*identifier`` or ``**identifier``. Functions may have "return" annotation of | 611 | 611 | the form "``-> expression``" after the parameter list. These annotations can be | 612 | 612 | any valid Python expression. The presence of annotations does not change the | 613 | | -semantics of a function. The annotation values are available as values of | 614 | | -a dictionary keyed by the parameters' names in the :attr:`__annotations__` | 615 | | -attribute of the function object. If the ``annotations`` import from | 616 | | -:mod:`__future__` is used, annotations are preserved as strings at runtime which | 617 | | -enables postponed evaluation. Otherwise, they are evaluated when the function | 618 | | -definition is executed. In this case annotations may be evaluated in | 619 | | -a different order than they appear in the source code. | | 613 | +semantics of a function. The annotation values are available as string values | | 614 | +in a dictionary keyed by the parameters' names in the :attr:`__annotations__` | | 615 | +attribute of the function object. | 620 | 616 |
| 621 | 617 | .. index:: pair: lambda; expression | 622 | 618 |
| |
Collapse file Copy file name to clipboardExpand all lines: Doc/whatsnew/3.10.rst +17Lines changed: 17 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -70,6 +70,23 @@ Summary -- Release highlights | 70 | 70 | New Features | 71 | 71 | ============ | 72 | 72 |
| | 73 | +.. _whatsnew310-pep563: | | 74 | + | | 75 | +PEP 563: Postponed Evaluation of Annotations Becomes Default | | 76 | +------------------------------------------------------------ | | 77 | + | | 78 | +In Python 3.7, postponed evaluation of annotations was added, | | 79 | +to be enabled with a ``from __future__ import annotations`` | | 80 | +directive. In 3.10 this became the default behavior, even | | 81 | +without that future directive. With this being default, all | | 82 | +annotations stored in :attr:`__annotations__` will be strings. | | 83 | +If needed, annotations can be resolved at runtime using | | 84 | +:func:`typing.get_type_hints`. See :pep:`563` for a full | | 85 | +description. Also, the :func:`inspect.signature` will try to | | 86 | +resolve types from now on, and when it fails it will fall back to | | 87 | +showing the string annotations. (Contributed by Batuhan Taskaya | | 88 | +in :issue:`38605`.) | | 89 | + | 73 | 90 | * The :class:`int` type has a new method :meth:`int.bit_count`, returning the | 74 | 91 | number of ones in the binary expansion of a given integer, also known | 75 | 92 | as the population count. (Contributed by Niklas Fiekas in :issue:`29882`.) | |
Collapse file Copy file name to clipboardExpand all lines: Lib/dataclasses.py +10-3Lines changed: 10 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -399,8 +399,10 @@ def _create_fn(name, args, body, *, globals=None, locals=None, | 399 | 399 |
| 400 | 400 | ns = {} | 401 | 401 | exec(txt, globals, ns) | 402 | | - return ns['__create_fn__'](**locals) | 403 | | - | | 402 | + func = ns['__create_fn__'](**locals) | | 403 | + for arg, annotation in func.__annotations__.copy().items(): | | 404 | + func.__annotations__[arg] = locals[annotation] | | 405 | + return func | 404 | 406 |
| 405 | 407 | def _field_assign(frozen, name, value, self_name): | 406 | 408 | # If we're a frozen class, then assign to our fields in __init__ | @@ -651,6 +653,11 @@ def _is_type(annotation, cls, a_module, a_type, is_type_predicate): | 651 | 653 | # a eval() penalty for every single field of every dataclass | 652 | 654 | # that's defined. It was judged not worth it. | 653 | 655 |
| | 656 | + # Strip away the extra quotes as a result of double-stringifying when the | | 657 | + # 'annotations' feature became default. | | 658 | + if annotation.startswith(("'", '"')) and annotation.endswith(("'", '"')): | | 659 | + annotation = annotation[1:-1] | | 660 | + | 654 | 661 | match = _MODULE_IDENTIFIER_RE.match(annotation) | 655 | 662 | if match: | 656 | 663 | ns = None | @@ -991,7 +998,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): | 991 | 998 | if not getattr(cls, '__doc__'): | 992 | 999 | # Create a class doc-string. | 993 | 1000 | cls.__doc__ = (cls.__name__ + | 994 | | - str(inspect.signature(cls)).replace(' -> None', '')) | | 1001 | + str(inspect.signature(cls)).replace(' -> NoneType', '')) | 995 | 1002 |
| 996 | 1003 | abc.update_abstractmethods(cls) | 997 | 1004 |
| |
Collapse file Copy file name to clipboardExpand all lines: Lib/inspect.py +17-2Lines changed: 17 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 45 | 45 | import tokenize | 46 | 46 | import token | 47 | 47 | import types | | 48 | +import typing | 48 | 49 | import warnings | 49 | 50 | import functools | 50 | 51 | import builtins | @@ -1877,7 +1878,10 @@ def _signature_is_functionlike(obj): | 1877 | 1878 | code = getattr(obj, '__code__', None) | 1878 | 1879 | defaults = getattr(obj, '__defaults__', _void) # Important to use _void ... | 1879 | 1880 | kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here | 1880 | | - annotations = getattr(obj, '__annotations__', None) | | 1881 | + try: | | 1882 | + annotations = _get_type_hints(obj) | | 1883 | + except AttributeError: | | 1884 | + annotations = None | 1881 | 1885 |
| 1882 | 1886 | return (isinstance(code, types.CodeType) and | 1883 | 1887 | isinstance(name, str) and | @@ -2118,6 +2122,16 @@ def p(name_node, default_node, default=empty): | 2118 | 2122 |
| 2119 | 2123 | return cls(parameters, return_annotation=cls.empty) | 2120 | 2124 |
| | 2125 | +def _get_type_hints(func): | | 2126 | + try: | | 2127 | + return typing.get_type_hints(func) | | 2128 | + except Exception: | | 2129 | + # First, try to use the get_type_hints to resolve | | 2130 | + # annotations. But for keeping the behavior intact | | 2131 | + # if there was a problem with that (like the namespace | | 2132 | + # can't resolve some annotation) continue to use | | 2133 | + # string annotations | | 2134 | + return func.__annotations__ | 2121 | 2135 |
| 2122 | 2136 | def _signature_from_builtin(cls, func, skip_bound_arg=True): | 2123 | 2137 | """Private helper function to get signature for | @@ -2161,7 +2175,8 @@ def _signature_from_function(cls, func, skip_bound_arg=True): | 2161 | 2175 | positional = arg_names[:pos_count] | 2162 | 2176 | keyword_only_count = func_code.co_kwonlyargcount | 2163 | 2177 | keyword_only = arg_names[pos_count:pos_count + keyword_only_count] | 2164 | | - annotations = func.__annotations__ | | 2178 | + annotations = _get_type_hints(func) | | 2179 | + | 2165 | 2180 | defaults = func.__defaults__ | 2166 | 2181 | kwdefaults = func.__kwdefaults__ | 2167 | 2182 |
| |
Collapse file Copy file name to clipboardExpand all lines: Lib/test/dataclass_module_1.py -6Lines changed: 0 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -#from __future__ import annotations | 2 | | -USING_STRINGS = False | 3 | | - | 4 | | -# dataclass_module_1.py and dataclass_module_1_str.py are identical | 5 | | -# except only the latter uses string annotations. | 6 | | - | 7 | 1 | import dataclasses | 8 | 2 | import typing | 9 | 3 |
| |
Collapse file Copy file name to clipboardExpand all lines: Lib/test/dataclass_module_1_str.py -32Lines changed: 0 additions & 32 deletions Collapse file Copy file name to clipboardExpand all lines: Lib/test/dataclass_module_2.py -6Lines changed: 0 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -#from __future__ import annotations | 2 | | -USING_STRINGS = False | 3 | | - | 4 | | -# dataclass_module_2.py and dataclass_module_2_str.py are identical | 5 | | -# except only the latter uses string annotations. | 6 | | - | 7 | 1 | from dataclasses import dataclass, InitVar | 8 | 2 | from typing import ClassVar | 9 | 3 |
| |
Collapse file Copy file name to clipboardExpand all lines: Lib/test/dataclass_module_2_str.py -32Lines changed: 0 additions & 32 deletions Collapse file Copy file name to clipboardExpand all lines: Lib/test/dataclass_textanno.py -2Lines changed: 0 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -from __future__ import annotations | 2 | | - | 3 | 1 | import dataclasses | 4 | 2 |
| 5 | 3 |
| |
|