Skip to content

Commit

Permalink
Support ast.Constant
Browse files Browse the repository at this point in the history
  • Loading branch information
serge-sans-paille committed Feb 8, 2019
1 parent fc47496 commit f2051c1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
8 changes: 6 additions & 2 deletions gast/gast.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def create_node(self, *args, **kwargs):
'FormattedValue': (('value', 'conversion', 'format_spec',),
('lineno', 'col_offset',), (expr,)),
'JoinedStr': (('values',), ('lineno', 'col_offset',), (expr,)),
'Constant': (('value',), ('lineno', 'col_offset',), (expr,)),
'Bytes': (('s',), ('lineno', 'col_offset',),
(expr,)),
'NameConstant': (('value',), ('lineno', 'col_offset',),
Expand Down Expand Up @@ -256,11 +257,14 @@ def literal_eval(node_or_string):


def get_docstring(node, clean=True):
import sys
if not isinstance(node, (FunctionDef, ClassDef, Module)):
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
DocStringTy = Str if sys.version_info[:2] < (3, 8) else Constant
if node.body and isinstance(node.body[0], Expr) and \
isinstance(node.body[0].value, Str):
isinstance(node.body[0].value, DocStringTy):
if clean:
import inspect
return inspect.cleandoc(node.body[0].value.s)
holder = node.body[0].value
return inspect.cleandoc(getattr(holder, holder._fields[0]))
return node.body[0].value.s
8 changes: 6 additions & 2 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@ def test_walk(self):
code = 'x + 1'
tree = gast.parse(code, mode='eval')
dump = gast.dump(tree)
norm = ("Expression(body=BinOp(left=Name(id='x', ctx=Load(), "
"annotation=None), op=Add(), right=Num(n=1)))")
if sys.version_info[:2] < (3, 8):
norm = ("Expression(body=BinOp(left=Name(id='x', ctx=Load(), "
"annotation=None), op=Add(), right=Num(n=1)))")
else:
norm = ("Expression(body=BinOp(left=Name(id='x', ctx=Load(), "
"annotation=None), op=Add(), right=Constant(value=1)))")
self.assertEqual(dump, norm)
self.assertEqual(len(list(gast.walk(tree))), 6)

Expand Down

0 comments on commit f2051c1

Please sign in to comment.