Python integration
Calling Python from Codon is possible in two ways:
from python import
allows importing and calling Python functions from existing Python modules.@python
allows writing Python code directly in Codon.
In order to use these features, the CODON_PYTHON
environment variable must be set to the appropriate Python shared library:
For example, with a brew
-installed Python 3.9 on macOS, this might be
Note that only Python versions 3.6 and later are supported.
from python import
from python import
Let's say we have a Python function defined in mymodule.py:
We can call this function in Codon using from python import
and indicating the appropriate call and return types:
(Be sure the PYTHONPATH
environment variable includes the path of mymodule.py!)
from python import
does not need to specify explicit types, in which case Codon will operate directly on the Python objects, and convert Codon types to Python types as necessary:
@python
@python
Codon programs can contain functions that will be executed by Python via pydef
:
This makes calling Python modules like NumPy very easy:
Data conversions
Codon uses two new magic methods to transfer data to and from Python:
__to_py__
: Produces a Python object (PyObject*
in C) given a Codon object.__from_py__
: Produces a Codon object given a Python object.
Codon stores the results of __to_py__
calls by wrapping them in an instance of a new class called pyobj
, which correctly handles the underlying Python object's reference count. All operations on pyobj
s then go through CPython's API.
Last updated