[Python-checkins] gh-95066: ast: Replace assert with ValueError (GH-95072)

ambv webhook-mailer at python.org
Tue Jul 26 05:43:17 EDT 2022


https://github.com/python/cpython/commit/a5dde0fe4fa13b4ccfec4e27502b19bbbb7e5bb0
commit: a5dde0fe4fa13b4ccfec4e27502b19bbbb7e5bb0
branch: main
author: Shantanu <12621235+hauntsaninja at users.noreply.github.com>
committer: ambv <lukasz at langa.pl>
date: 2022-07-26T11:43:09+02:00
summary:

gh-95066: ast: Replace assert with ValueError (GH-95072)

Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>

files:
A Misc/NEWS.d/next/Library/2022-07-20-22-49-48.gh-issue-95066.TuCu0E.rst
M Lib/ast.py
M Lib/test/test_ast.py

diff --git a/Lib/ast.py b/Lib/ast.py
index 4e2ae859245f9..ebf4529f79b06 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -42,7 +42,8 @@ def parse(source, filename='<unknown>', mode='exec', *,
         flags |= PyCF_TYPE_COMMENTS
     if isinstance(feature_version, tuple):
         major, minor = feature_version  # Should be a 2-tuple.
-        assert major == 3
+        if major != 3:
+            raise ValueError(f"Unsupported major version: {major}")
         feature_version = minor
     elif feature_version is None:
         feature_version = -1
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 9734218c21be3..de34ccff2ef05 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -756,6 +756,12 @@ def test_assignment_expression_feature_version(self):
         with self.assertRaises(SyntaxError):
             ast.parse('(x := 0)', feature_version=(3, 7))
 
+    def test_invalid_major_feature_version(self):
+        with self.assertRaises(ValueError):
+            ast.parse('pass', feature_version=(2, 7))
+        with self.assertRaises(ValueError):
+            ast.parse('pass', feature_version=(4, 0))
+
     def test_constant_as_name(self):
         for constant in "True", "False", "None":
             expr = ast.Expression(ast.Name(constant, ast.Load()))
diff --git a/Misc/NEWS.d/next/Library/2022-07-20-22-49-48.gh-issue-95066.TuCu0E.rst b/Misc/NEWS.d/next/Library/2022-07-20-22-49-48.gh-issue-95066.TuCu0E.rst
new file mode 100644
index 0000000000000..05ae4a6a2761a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-07-20-22-49-48.gh-issue-95066.TuCu0E.rst
@@ -0,0 +1 @@
+Replaced assert with exception in :func:`ast.parse`, when ``feature_version`` has an invalid major version. Patch by Shantanu Jain.



More information about the Python-checkins mailing list