Skip to content

Commit

Permalink
Update unparser for py 3.12 and setup minimal testing
Browse files Browse the repository at this point in the history
Finally fixes #79
  • Loading branch information
serge-sans-paille committed Nov 15, 2023
1 parent a79e813 commit ed5faef
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
28 changes: 28 additions & 0 deletions gast/unparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,8 @@ def visit_ClassDef(self, node):
self.fill("@")
self.traverse(deco)
self.fill("class " + node.name)
if hasattr(node, "type_params"):
self._type_params_helper(node.type_params)
with self.delimit_if("(", ")", condition = node.bases or node.keywords):
comma = False
for e in node.bases:
Expand Down Expand Up @@ -443,6 +445,8 @@ def _function_helper(self, node, fill_suffix):
self.traverse(deco)
def_str = fill_suffix + " " + node.name
self.fill(def_str)
if hasattr(node, "type_params"):
self._type_params_helper(node.type_params)
with self.delimit("(", ")"):
self.traverse(node.args)
if node.returns:
Expand All @@ -451,6 +455,30 @@ def _function_helper(self, node, fill_suffix):
with self.block(extra=self.get_type_comment(node)):
self._write_docstring_and_traverse_body(node)

def _type_params_helper(self, type_params):
if type_params is not None and len(type_params) > 0:
with self.delimit("[", "]"):
self.interleave(lambda: self.write(", "), self.traverse, type_params)

def visit_TypeVar(self, node):
self.write(node.name)
if node.bound:
self.write(": ")
self.traverse(node.bound)

def visit_TypeVarTuple(self, node):
self.write("*" + node.name)

def visit_ParamSpec(self, node):
self.write("**" + node.name)

def visit_TypeAlias(self, node):
self.fill("type ")
self.traverse(node.name)
self._type_params_helper(node.type_params)
self.write(" = ")
self.traverse(node.value)

def visit_For(self, node):
self._for_helper("for ", node)

Expand Down
37 changes: 37 additions & 0 deletions tests/test_unparser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import unittest

import ast
import gast
import sys


class UnparserTestCase(unittest.TestCase):

def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self.maxDiff = None

def assertUnparse(self, code):
normalized_code = ast.unparse(ast.parse(code))
tree = gast.parse(normalized_code)
compile(gast.gast_to_ast(tree), '<test>', 'exec')
unparsed = gast.unparse(tree)
self.assertEqual(normalized_code, unparsed)

def test_FunctionDef(self):
self.assertUnparse('def foo(x, y): return x, y')

def test_BinaryOp(self):
self.assertUnparse('1 + 3')

if sys.version_info >= (3, 12):

def test_TypeParameter(self):
self.assertUnparse('type x[T] = list[T]')


if sys.version_info < (3, 9):
del UnparserTestCase

if __name__ == '__main__':
unittest.main()

0 comments on commit ed5faef

Please sign in to comment.