Pseudocode to Python translation

The vc2_pseudocode_parser.python_transformer module and vc2-pseudocode-to-python command line tool automatically translate pseudocode listings into valid Python.

In general, the translation between pseudocode and Python is ‘obvious’. The only non-obvious part, perhaps, is that labels are translated into Python string literals. The output is pretty-printed in a style similar to the Black code style with comments and vertical whitespace retained (in a semi-normalised fashion).

For example, the following pseudocode:

add(a, b, c):
    # A function which adds three numbers together
    total = 0  # An accumulator
    for each n in a, b, c:
        total += n
    return total

update_state(state):
    state[count] += 1

Is translated in the the following Python:

def add(a, b, c):
    """
    A function which adds three numbers together
    """
    total = 0  # An accumulator
    for n in [a, b, c]:
        total += n
    return total


def update_state(state):
    state["count"] += 1

Command-line utility

The vc2-pseudocode-to-python command line utility is provided which can convert a pseudocode listing into Python.

Example usage:

$ vc2-pseudocode-to-python input.pc output.py

Python API

The pseudocode_to_python() utility function may be used to directly translate pseudocode into Python.

pseudocode_to_python(pseudocode_source, indent='    ', generate_docstrings=True, add_translation_note=False)

Transform a pseudocode listing into Python.

Will throw a ParseError or ASTConstructionError if the supplied pseudocode contains syntactic errors.

Parameters
pseudocode_sourcestr

The pseudocode source code to translate.

indentstr

The string to use for indentation in the generated Python source. Defaults to four spaces.

generate_docstringsbool

If True, the first block of comments in the file and each function will be converted into a docstring. Otherwise they’ll be left as ordinary comments. Defaulse to True.

add_translation_notebool

If True, adds a comment to the top of the generated output indicating that this file was automatically translated from the pseudocode. Defaulse to False.

Example usage:

>>> from vc2_pseudocode_parser.python_transformer import pseudocode_to_python

>>> print(pseudocode_to_python("""
...     foo(state, a):
...         state[bar] = a + 1
... """))
def foo(state, a):
    state["bar"] = a + 1