This module provides functionality to generate directly compilable code from Sympy expressions. The codegen function is the user interface to the code generation functionality in Sympy. Some details of the implementation is given below for advanced users that may want to use the framework directly.


The codegen callable is not in the sympy namespace automatically, to use it you must first execute

>>> from sympy.utilities.codegen import codegen

User interface

sympy.utilities.codegen.codegen(name_expr, language, prefix, project='project', to_files=False, header=True, empty=True, argument_sequence=None)[source]

Write source code for the given expressions in the given language.

Mandatory Arguments:
A single (name, expression) tuple or a list of (name, expression) tuples. Each tuple corresponds to a routine. If the expression is an equality (an instance of class Equality) the left hand side is considered an output argument.
A string that indicates the source code language. This is case insensitive. For the moment, only ‘C’ and ‘F95’ is supported.
A prefix for the names of the files that contain the source code. Proper (language dependent) suffixes will be appended.
Optional Arguments:
A project name, used for making unique preprocessor instructions. [DEFAULT=”project”]
When True, the code will be written to one or more files with the given prefix, otherwise strings with the names and contents of these files are returned. [DEFAULT=False]
When True, a header is written on top of each source file. [DEFAULT=True]
When True, empty lines are used to structure the code. [DEFAULT=True]

sequence of arguments for the routine in a preferred order. A CodeGenError is raised if required arguments are missing. Redundant arguments are used without warning.

If omitted, arguments will be ordered alphabetically, but with all input aguments first, and then output or in-out arguments.

>>> from sympy import symbols
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(c_name, c_code), (h_name, c_header)] = \
...     codegen(("f", x+y*z), "C", "test", header=False, empty=False)
>>> print c_name
>>> print c_code,
#include "test.h"
#include <math.h>
double f(double x, double y, double z) {
  return x + y*z;
>>> print h_name
>>> print c_header,
#ifndef PROJECT__TEST__H
#define PROJECT__TEST__H
double f(double x, double y, double z);

Impementation Details

Here we present the most important pieces of the internal structure, as advanced users may want to use it directly, for instance by subclassing a code generator for a specialized application. It is very likely that you would prefer to use the codegen() function documented above.

Basic assumptions:

  • A generic Routine data structure describes the routine that must be translated into C/Fortran/... code. This data structure covers all features present in one or more of the supported languages.
  • Descendants from the CodeGen class transform multiple Routine instances into compilable code. Each derived class translates into a specific language.
  • In many cases, one wants a simple workflow. The friendly functions in the last part are a simple api on top of the Routine/CodeGen stuff. They are easier to use, but are less powerful.


The Routine class is a very important piece of the codegen module. Viewing the codegen utility as a translator of mathematical expressions into a set of statements in a programming language, the Routine instances are responsible for extracting and storing information about how the math can be encapsulated in a function call. Thus, it is the Routine constructor that decides what arguments the routine will need and if there should be a return value.

class sympy.utilities.codegen.Routine(name, expr, argument_sequence=None)[source]

Generic description of an evaluation routine for a set of sympy expressions.

A CodeGen class can translate instances of this class into C/Fortran/... code. The routine specification covers all the features present in these languages. The CodeGen part must raise an exception when certain features are not present in the target language. For example, multiple return values are possible in Python, but not in C or Fortran. Another example: Fortran and Python support complex numbers, while C does not.

__init__(name, expr, argument_sequence=None)[source]

Initialize a Routine instance.

A string with the name of this routine in the generated code
The sympy expression that the Routine instance will represent. If given a list or tuple of expressions, the routine will be considered to have multiple return values.
Optional list/tuple containing arguments for the routine in a preferred order. If omitted, arguments will be ordered alphabetically, but with all input aguments first, and then output or in-out arguments.

A decision about whether to use output arguments or return values, is made depending on the mathematical expressions. For an expression of type Equality, the left hand side is made into an OutputArgument (or an InOutArgument if appropriate). Else, the calculated expression is the return values of the routine.

A tuple of exressions can be used to create a routine with both return value(s) and output argument(s).


Returns a list of OutputArgument, InOutArgument and Result.

If return values are present, they are at the end ot the list.

CodeGen and subclasses

The method that activates the code generation is Codegen.write()

CodeGen.write(routines, prefix, to_files=False, header=True, empty=True)[source]

Writes all the source code files for the given routines.

The generate source is returned as a list of (filename, contents) tuples, or is written to files (see options). Each filename consists of the given prefix, appended with an appropriate extension.

A list of Routine instances to be written
The prefix for the output files
When True, the output is effectively written to files. [DEFAULT=False] Otherwise, a list of (filename, contents) tuples is returned.
When True, a header comment is included on top of each source file. [DEFAULT=True]
When True, empty lines are included to structure the source files. [DEFAULT=True]

Each programming language is generated by subclasses of CodeGen.

class sympy.utilities.codegen.FCodeGen(project='project')[source]

Generator for Fortran 95 code

The .write() method inherited from CodeGen will output a code file and an inteface file, <prefix>.f90 and <prefix>.h respectively.

class sympy.utilities.codegen.CCodeGen(project='project')[source]

Generator for C code

The .write() method inherited from CodeGen will output a code file and an inteface file, <prefix>.c and <prefix>.h respectively.

Table Of Contents

Previous topic

Autowrap module

Next topic


This Page