how to generate python code

Solutions on MaxInterview for how to generate python code by the best coders in the world

showing results for - "how to generate python code"
Tom
06 Aug 2020
1class CodeGenerator:
2    def __init__(self, indentation='\t'):
3        self.indentation = indentation
4        self.level = 0
5        self.code = ''
6
7    def indent(self):
8        self.level += 1
9
10    def dedent(self):
11        if self.level > 0:
12            self.level -= 1
13
14    def __add__(self, value):
15        temp = CodeGenerator(indentation=self.indentation)
16        temp.level = self.level
17        temp.code = str(self) + ''.join([self.indentation for i in range(0, self.level)]) + str(value)
18        return temp
19
20    def __str__(self):
21        return str(self.code)
22
23a = CodeGenerator()
24a += 'for a in range(1, 3):\n'
25a.indent()
26a += 'for b in range(4, 6):\n'
27a.indent()
28a += 'print(a * b)\n'
29a.dedent()
30a += '# pointless comment\n'
31print(a)
32