Last active
January 19, 2022 06:54
-
-
Save jayendra13/fa5794255421b2c8730e12911dbe09b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import astor | |
class MyListComp(ast.ListComp): | |
def __init__(self, target, value): | |
self._target = target | |
self._value = value | |
class MySourceGenerator(astor.SourceGenerator): | |
def visit_MyListComp(self, node): | |
value, target = node._value, node._target | |
self.write(f"{target.id} = []") | |
self.newline() | |
self.visit(value.generators[0]) | |
self.newline() | |
self.indentation += 1 | |
self.write(f"{target.id}.append") | |
self.visit(value.elt) | |
self.indentation -= 1 | |
class ListCompTransformer(ast.NodeTransformer): | |
def visit_Assign(self, node): | |
if isinstance(node.value, ast.ListComp): | |
return MyListComp(node.targets[0], node.value) | |
return node | |
def main(): | |
x = """a = [2*x for x in range(10)]""" | |
tf = ListCompTransformer().visit(ast.parse(x)) | |
print(astor.to_source(tf, source_generator_class=MySourceGenerator)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment