def to_source(node):
"""
Convert a node to source code by converting it to an astroid tree first, and using astroid's
as_string() method.
"""
if hasattr(node, 'as_string'):
return node.as_string()
builder = astroid.rebuilder.TreeRebuilder(astroid.manager.AstroidManager())
# We need to make a deep copy of node; not sure why, but node seems affected by the astroid
# TreeRebuilder.
node_copy = copy.deepcopy(node)
if isinstance(node, ast.Module):
anode = builder.visit_module(node_copy, '', '', '')
else:
# Anything besides Module needs to have astroid Module passed in as a parent.
amodule = astroid.nodes.Module('', None)
anode = builder.visit(node_copy, amodule)
return anode.as_string()
评论列表
文章目录