comedy.compiler — Veeyu to Python compiler

class comedy.compiler.CodeGenerator(parent=None, startline=None)

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:
  • parent (CodeGenerator) – an optional parent CodeGenerator instance. only internally used parameter
  • startline (str) – an optional first line of the block. only internally used parameter
buffer

An internal buffer.

indentation

The internal state stores an indentation level.

INDENTATION

The string constant contains whitespace characters for indentations.

code

A generated code string.

write(code)

Writes a code. It’s not aware to indentation status.

Parameters:code (str) – a code to write
writeln(code)

Writes a code by line. It’s aware to indentation status.

Parameters:code (str) – a code to write
newline()

Write a new line.

indent()

Indents by one.

outdent(step=1)

Outdents by step.

Parameters:step (int) – an outdenting step. default is 1
block(line)

Controls a code block using with keyword.

Parameters:line (str) – a first line of the code block e.g. 'if cond:'
flush()

Flushes a buffer contains generated codes.

Returns:a buffer contains generated codes
Return type:str

Project Versions

Previous topic

comedy.visitor — Simple visitor pattern

Next topic

comedy.object — Runtime objects

This Page