bpo-35975: Support parsing earlier minor versions of Python 3 (GH-12086)
This adds a `feature_version` flag to `ast.parse()` (documented) and `compile()` (hidden) that allow tweaking the parser to support older versions of the grammar. In particular if `feature_version` is 5 or 6, the hacks for the `async` and `await` keyword from PEP 492 are reinstated. (For 7 or higher, these are unconditionally treated as keywords, but they are still special tokens rather than `NAME` tokens that the parser driver recognizes.)
https://bugs.python.org/issue35975
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index 3df7f9e..1884bea 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -126,7 +126,7 @@
Apart from the node classes, the :mod:`ast` module defines these utility functions
and classes for traversing abstract syntax trees:
-.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False)
+.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=-1)
Parse the source into an AST node. Equivalent to ``compile(source,
filename, mode, ast.PyCF_ONLY_AST)``.
@@ -145,13 +145,19 @@
modified to correspond to :pep:`484` "signature type comments",
e.g. ``(str, int) -> List[str]``.
+ Also, setting ``feature_version`` to the minor version of an
+ earlier Python 3 version will attempt to parse using that version's
+ grammar. For example, setting ``feature_version=4`` will allow
+ the use of ``async`` and ``await`` as variable names. The lowest
+ supported value is 4; the highest is ``sys.version_info[1]``.
+
.. warning::
It is possible to crash the Python interpreter with a
sufficiently large/complex string due to stack depth limitations
in Python's AST compiler.
.. versionchanged:: 3.8
- Added ``type_comments=True`` and ``mode='func_type'``.
+ Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
.. function:: literal_eval(node_or_string)
diff --git a/Doc/library/token-list.inc b/Doc/library/token-list.inc
index cb9fcd7..877d39a 100644
--- a/Doc/library/token-list.inc
+++ b/Doc/library/token-list.inc
@@ -203,6 +203,10 @@
.. data:: OP
+.. data:: AWAIT
+
+.. data:: ASYNC
+
.. data:: TYPE_IGNORE
.. data:: TYPE_COMMENT
diff --git a/Doc/library/token.rst b/Doc/library/token.rst
index 4936e9a..5c641ef 100644
--- a/Doc/library/token.rst
+++ b/Doc/library/token.rst
@@ -88,3 +88,6 @@
.. versionchanged:: 3.8
Added :data:`TYPE_COMMENT`.
+ Added :data:`AWAIT` and :data:`ASYNC` tokens back (they're needed
+ to support parsing older Python versions for :func:`ast.parse` with
+ ``feature_version`` set to 6 or lower).