Python code generator. You can control code blocks using with and block() method:
>>> cg = CodeGenerator()
>>> with cg.block('if 1:') as b:
... b.writeln('print 1')
... with b.block('if 2:') as b2:
... with b2.block('if 3:') as b3:
... pass
...
>>> cg.writeln('print 2')
>>> print cg.flush()
if 1:
print 1
if 2:
if 3:
pass
print 2
<BLANKLINE>
You can micro-control code blocks using indent() and outdent() methods if you want:
>>> cg.writeln('if 0:')
>>> cg.indent()
>>> cg.writeln('print 3')
>>> cg.outdent()
>>> cg.writeln('print 4')
>>> print cg.flush()
if 0:
print 3
print 4
<BLANKLINE>
Parameters: |
|
---|
An internal buffer.
The internal state stores an indentation level.
The string constant contains whitespace characters for indentations.
A generated code string.
Writes a code. It’s not aware to indentation status.
Parameters: | code (str) – a code to write |
---|
Writes a code by line. It’s aware to indentation status.
Parameters: | code (str) – a code to write |
---|
Write a new line.
Indents by one.
Outdents by step.
Parameters: | step (int) – an outdenting step. default is 1 |
---|
Controls a code block using with keyword.
Parameters: | line (str) – a first line of the code block e.g. 'if cond:' |
---|
Flushes a buffer contains generated codes.
Returns: | a buffer contains generated codes |
---|---|
Return type: | str |