google / python-fire

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Other
26.95k stars 1.44k forks source link

Replace deprecated usage of ast.Str #523

Closed wdhongtw closed 1 month ago

wdhongtw commented 2 months ago

Motivation

This tool depends on ast.Str to wrap any value other than True, False and None, which is going to be removed in Python 3.14 (probably in less than one year).

Before the day that Python 3.14 is released, it would be great to change the usage of ast.Str to ast.Constant (added in Python 3.8), and make a new release. With this change, we can make sure the fire library still works after Python 3.14 is released.

Possible Solution

It could be solve quickly by one-line change, although we need conditional import to preserve backward compatibility.

diff --git a/fire/parser.py b/fire/parser.py
index 2aff8bd..bdf3cdb 100644
--- a/fire/parser.py
+++ b/fire/parser.py
@@ -20,7 +20,12 @@ from __future__ import print_function

 import argparse
 import ast
+import sys

+if sys.version_info[0:2] < (3, 8):
+  _StrNode = ast.Str
+else:
+  _StrNode = ast.Constant

 def CreateParser():
   parser = argparse.ArgumentParser(add_help=False)
@@ -127,4 +132,4 @@ def _Replacement(node):
   # These are the only builtin constants supported by literal_eval.
   if value in ('True', 'False', 'None'):
     return node
-  return ast.Str(value)
+  return _StrNode(value)

All existing test cases passed.

If this change looks reasonable, I could submit a PR for this, saving the time for maintainer. :D

References

dbieber commented 1 month ago

Thank you.