Tools for Source Code Generation

class pytools.codegen.CodeGenerator[source]

Language-agnostic functionality for source code generation.

extend(sub_generator)[source]
Parameters

sub_generator (pytools.codegen.CodeGenerator) –

Return type

None

get()[source]
Return type

str

add_to_preamble(s)[source]
Parameters

s (str) –

Return type

None

__call__(s)[source]

Call self as a function.

Parameters

s (str) –

Return type

None

indent()[source]
Return type

None

dedent()[source]
Return type

None

class pytools.codegen.Indentation(generator)[source]

A context manager for indentation for use with CodeGenerator.

generator
__enter__()[source]
Return type

None

__exit__(exc_type, exc_val, exc_tb)[source]
Parameters
  • exc_type (Any) –

  • exc_val (Any) –

  • exc_tb (Any) –

Return type

None

pytools.codegen.remove_common_indentation(code, require_leading_newline=True)[source]

Remove leading indentation from one or more lines of code.

Removes an amount of indentation equal to the indentation level of the first nonempty line in code.

Parameters
  • code (str) – Input string.

  • require_leading_newline (bool) – If True, only remove indentation if code starts with \n.

Returns

A copy of code stripped of leading common indentation.