mirror of https://github.com/exaloop/codon.git
Update docs
parent
07073dbf66
commit
d587bbbe42
|
@ -39,6 +39,16 @@ print(multiply(3, 4)) # 12
|
|||
(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
|
||||
from python import numpy as np # Codon will call NumPy through CPython's API
|
||||
x = np.array([1, 2, 3, 4]) * 10
|
||||
print(x) # [10 20 30 40]
|
||||
```
|
||||
|
||||
# `@python`
|
||||
|
||||
Codon programs can contain functions that will be executed by Python via
|
||||
|
@ -62,3 +72,24 @@ def myrange(n: int) -> List[int]:
|
|||
|
||||
print(myrange(5)) # [0, 1, 2, 3, 4]
|
||||
```
|
||||
|
||||
# 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.
|
||||
|
||||
``` python
|
||||
import python # needed to initialize the Python runtime
|
||||
|
||||
o = (42).__to_py__() # type of 'o' is 'cobj', equivalent to a pointer in C
|
||||
print(o) # 0x100e00610
|
||||
|
||||
n = int.__from_py__(o)
|
||||
print(n) # 42
|
||||
```
|
||||
|
||||
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.
|
||||
|
|
Loading…
Reference in New Issue