File: code.py

package info (click to toggle)
python-peachpy 0.0~git20211013.257881e-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,452 kB
  • sloc: python: 29,286; ansic: 54; makefile: 44; cpp: 31
file content (48 lines) | stat: -rw-r--r-- 1,285 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# This file is part of PeachPy package and is licensed under the Simplified BSD license.
#    See license.rst for the full text of the license.

active_writer = None


class CodeWriter:
    def __init__(self):
        self.lines = list()
        self.indent = 0
        self.previous_writer = None

    def __enter__(self):
        global active_writer
        self.previous_writer = active_writer
        active_writer = self
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        global active_writer
        active_writer = self.previous_writer
        self.previous_writer = None

    def line(self, line="", indent=0):
        if line != "":
            self.lines.append("    "*(self.indent+int(indent)) + str(line))
        else:
            self.lines.append(line)

    def indent_line(self, line=""):
        self.line(line, indent=1)

    def __str__(self):
        return "\n".join(self.lines)


class CodeBlock:
    def __init__(self, indent=True):
        self.indent = bool(indent)

    def __enter__(self):
        global active_writer
        active_writer.indent += int(self.indent)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        global active_writer
        active_writer.indent -= int(self.indent)