1
0
mirror of https://github.com/exaloop/codon.git synced 2025-06-03 15:03:52 +08:00
codon/docs/sphinx/python.rst

67 lines
1.7 KiB
ReStructuredText
Raw Normal View History

Calling Python from Codon
=========================
2021-09-27 14:02:44 -04:00
Calling Python from Codon is possible in two ways:
2021-09-27 14:02:44 -04:00
- ``from python import`` allows importing and calling Python functions from existing Python modules.
- ``@python`` allows writing Python code directly in Codon.
2021-09-27 14:02:44 -04:00
In order to use these features, the ``CODON_PYTHON`` environment variable must be set to the appropriate
2021-09-27 14:02:44 -04:00
Python shared library:
.. code-block:: bash
export CODON_PYTHON=/path/to/libpython.X.Y.so
2021-09-27 14:02:44 -04:00
For example, with a ``brew``-installed Python 3.9 on macOS, this might be
.. code-block:: bash
/usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/lib/libpython3.9.dylib
Note that only Python versions 3.6 and later are supported.
2021-10-05 14:44:32 -04:00
``from python import``
----------------------
2021-09-27 14:02:44 -04:00
Let's say we have a Python function defined in *mymodule.py*:
.. code-block:: python
def multiply(a, b):
return a * b
We can call this function in Codon using ``from python import`` and indicating the appropriate
2021-09-27 14:02:44 -04:00
call and return types:
.. code-block:: python
2021-09-27 14:02:44 -04:00
from python import mymodule.multiply(int, int) -> int
print(multiply(3, 4)) # 12
(Be sure the ``PYTHONPATH`` environment variable includes the path of *mymodule.py*!)
2021-10-05 14:44:32 -04:00
``@python``
-----------
2021-09-27 14:02:44 -04:00
Codon programs can contain functions that will be executed by Python via ``pydef``:
2021-09-27 14:02:44 -04:00
.. code-block:: python
2021-09-27 14:02:44 -04:00
@python
def multiply(a: int, b: int) -> int:
return a * b
print(multiply(3, 4)) # 12
This makes calling Python modules like NumPy very easy:
.. code-block:: python
2021-09-27 14:02:44 -04:00
@python
def myrange(n: int) -> List[int]:
from numpy import arange
return list(arange(n))
print(myrange(5)) # [0, 1, 2, 3, 4]