Skip to content

Commit 391c64c

Browse files
authored
Merge pull request #278 from PyO3/examples-copy-editing
Copy-edit the examples for consistency
2 parents bff49a4 + ad5f583 commit 391c64c

File tree

19 files changed

+83
-83
lines changed

19 files changed

+83
-83
lines changed

.github/workflows/ci.yml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ jobs:
7777
- name: Test example
7878
run: |
7979
pip install nox
80-
nox -f examples/simple-extension/noxfile.py
80+
nox -f examples/simple/noxfile.py
8181
env:
8282
CARGO_TERM_VERBOSE: true
8383
CARGO_BUILD_TARGET: ${{ matrix.platform.rust-target }}
@@ -99,7 +99,7 @@ jobs:
9999
default: true
100100
- uses: Swatinem/rust-cache@v1
101101
with:
102-
working-directory: examples/simple-extension
102+
working-directory: examples/simple
103103
continue-on-error: true
104104
- name: Install toml
105105
run: pip install toml
@@ -112,11 +112,11 @@ jobs:
112112
cargo_toml["workspace"] = {}
113113
with open("Cargo.toml", "w") as f:
114114
toml.dump(cargo_toml, f)
115-
working-directory: examples/simple-extension
115+
working-directory: examples/simple
116116
shell: python
117117
- name: Generate lockfile
118118
run: cargo generate-lockfile
119-
working-directory: examples/simple-extension
119+
working-directory: examples/simple
120120
- name: Unify dependencies on ndarray to 0.13.1
121121
run: |
122122
import toml
@@ -126,12 +126,12 @@ jobs:
126126
if pkg["name"] == "ndarray" and pkg["version"] != "0.13.1":
127127
pkg_id = pkg["name"] + ":" + pkg["version"]
128128
subprocess.run(["cargo", "update", "--package", pkg_id, "--precise", "0.13.1"], check=True)
129-
working-directory: examples/simple-extension
129+
working-directory: examples/simple
130130
shell: python
131131
- name: Test example
132132
run: |
133133
pip install nox
134-
nox -f examples/simple-extension/noxfile.py
134+
nox -f examples/simple/noxfile.py
135135
136136
examples:
137137
runs-on: ubuntu-latest

README.md

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,9 @@ Rust bindings for the NumPy C-API.
2828

2929
### Write a Python module in Rust
3030

31-
Please see the [simple-extension](https://github.com/PyO3/rust-numpy/tree/main/examples/simple-extension)
32-
directory for the complete example.
31+
Please see the [simple](examples/simple) example for how to get started.
3332

34-
Also, we have an example project with [ndarray-linalg](https://github.com/PyO3/rust-numpy/tree/main/examples/linalg).
33+
There are also examples using [ndarray-linalg](examples/linalg) and [rayon](examples/parallel).
3534

3635
```toml
3736
[lib]
@@ -46,22 +45,23 @@ numpy = "0.15"
4645
```rust
4746
use numpy::ndarray::{ArrayD, ArrayViewD, ArrayViewMutD};
4847
use numpy::{IntoPyArray, PyArrayDyn, PyReadonlyArrayDyn};
49-
use pyo3::prelude::{pymodule, PyModule, PyResult, Python};
48+
use pyo3::{pymodule, types::PyModule, PyResult, Python};
5049

5150
#[pymodule]
5251
fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
53-
// immutable example
52+
// example using immutable borrows producing a new array
5453
fn axpy(a: f64, x: ArrayViewD<'_, f64>, y: ArrayViewD<'_, f64>) -> ArrayD<f64> {
5554
a * &x + &y
5655
}
5756

58-
// mutable example (no return)
57+
// example using a mutable borrow to modify an array in-place
5958
fn mult(a: f64, mut x: ArrayViewMutD<'_, f64>) {
6059
x *= a;
6160
}
6261

6362
// wrapper of `axpy`
64-
#[pyfn(m, "axpy")]
63+
#[pyfn(m)]
64+
#[pyo3(name = "axpy")]
6565
fn axpy_py<'py>(
6666
py: Python<'py>,
6767
a: f64,
@@ -74,7 +74,8 @@ fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
7474
}
7575

7676
// wrapper of `mult`
77-
#[pyfn(m, "mult")]
77+
#[pyfn(m)]
78+
#[pyo3(name = "mult")]
7879
fn mult_py(_py: Python<'_>, a: f64, x: &PyArrayDyn<f64>) -> PyResult<()> {
7980
let x = unsafe { x.as_array_mut() };
8081
mult(a, x);
@@ -98,23 +99,24 @@ numpy = "0.15"
9899

99100
```rust
100101
use numpy::PyArray1;
101-
use pyo3::prelude::{PyResult, Python};
102-
use pyo3::types::IntoPyDict;
102+
use pyo3::{types::IntoPyDict, PyResult, Python};
103103

104104
fn main() -> PyResult<()> {
105105
Python::with_gil(|py| {
106106
let np = py.import("numpy")?;
107107
let locals = [("np", np)].into_py_dict(py);
108+
108109
let pyarray: &PyArray1<i32> = py
109110
.eval("np.absolute(np.array([-1, -2, -3], dtype='int32'))", Some(locals), None)?
110111
.extract()?;
112+
111113
let readonly = pyarray.readonly();
112114
let slice = readonly.as_slice()?;
113115
assert_eq!(slice, &[1, 2, 3]);
116+
114117
Ok(())
115118
})
116119
}
117-
118120
```
119121

120122
## Dependency on ndarray
@@ -150,5 +152,6 @@ and [pull requests](https://github.com/PyO3/rust-numpy/pulls).
150152

151153
PyO3's [Contributing.md](https://github.com/PyO3/pyo3/blob/main/Contributing.md)
152154
is a nice guide for starting.
155+
153156
Also, we have a [Gitter](https://gitter.im/PyO3/Lobby) channel for communicating.
154157

examples/linalg/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[package]
2-
name = "numpy-linalg-example"
2+
name = "rust-linalg"
33
version = "0.1.0"
44
authors = ["Yuji Kanagawa <[email protected]>"]
55
edition = "2018"

examples/linalg/README.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
# rust-numpy example extension with linalg
1+
# rust-numpy extension using ndarray-linalg
22

3-
An example extension with [ndarray-linalg](https://github.com/rust-ndarray/ndarray-linalg).
3+
An example extension using [ndarray-linalg](https://github.com/rust-ndarray/ndarray-linalg).
44

55
Will link against a system-provided OpenBLAS.
66

7-
See [simple-extension's README](https://github.com/PyO3/rust-numpy/blob/main/examples/simple-extension/README.md)
8-
for an introduction.
7+
See the [README](../simple/README.md) of the simple extension for more information.

examples/linalg/noxfile.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33

44
@nox.session
55
def tests(session):
6-
session.install('pip', 'numpy', 'pytest')
7-
session.run('pip', 'install', '.', '-v')
8-
session.run('pytest')
6+
session.install("pip", "numpy", "pytest")
7+
session.run("pip", "install", ".", "-v")
8+
session.run("pytest")

examples/linalg/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use ndarray_linalg::solve::Inverse;
22
use numpy::{IntoPyArray, PyArray2, PyReadonlyArray2};
3-
use pyo3::{exceptions::PyRuntimeError, pymodule, types::PyModule, PyErr, PyResult, Python};
3+
use pyo3::{exceptions::PyRuntimeError, pymodule, types::PyModule, PyResult, Python};
44

55
#[pymodule]
66
fn rust_linalg(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
@@ -9,7 +9,7 @@ fn rust_linalg(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
99
let x = x.as_array();
1010
let y = x
1111
.inv()
12-
.map_err(|e| PyErr::new::<PyRuntimeError, _>(format!("[rust_linalg] {}", e)))?;
12+
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
1313
Ok(y.into_pyarray(py))
1414
}
1515
Ok(())

examples/linalg/tests/test_linalg.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33

44

55
def test_inv():
6-
x = np.array([
7-
[1, 0],
8-
[0, 2],
9-
], dtype=np.float64)
6+
x = np.array(
7+
[
8+
[1, 0],
9+
[0, 2],
10+
],
11+
dtype=np.float64,
12+
)
1013
y = rust_linalg.inv(x)
1114
np.testing.assert_array_almost_equal(y, np.linalg.inv(x))

examples/parallel/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[package]
2-
name = "numpy-parallel-example"
2+
name = "rust-parallel"
33
version = "0.1.0"
44
authors = ["Yuji Kanagawa <[email protected]>"]
55
edition = "2018"

examples/parallel/README.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
# rust-numpy example extension using optional ndarray features
1+
# rust-numpy extension using optional ndarray features
22

3-
An example extension using [optional ndarray features](https://docs.rs/ndarray/latest/ndarray/doc/crate_feature_flags/index.html), parallel execution using Rayon and optimized kernels using BLAS in this case.
4-
5-
See [simple-extension's README](https://github.com/PyO3/rust-numpy/blob/main/examples/simple-extension/README.md)
6-
for an introduction.
3+
An example extension using [optional ndarray features](https://docs.rs/ndarray/latest/ndarray/doc/crate_feature_flags/index.html), in this case parallel execution using Rayon and optimized kernels using BLAS.
74

5+
See the [README](../simple/README.md) of the simple extension for more information.

examples/parallel/noxfile.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33

44
@nox.session
55
def tests(session):
6-
session.install('pip', 'numpy', 'pytest')
7-
session.run('pip', 'install', '.', '-v')
8-
session.run('pytest')
6+
session.install("pip", "numpy", "pytest")
7+
session.run("pip", "install", ".", "-v")
8+
session.run("pytest")

examples/parallel/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// We need to link `blas_src` directly, c.f. https://github.com/rust-ndarray/ndarray#how-to-enable-blas-integration
22
extern crate blas_src;
33

4-
use ndarray::Zip;
4+
use numpy::ndarray::Zip;
55
use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1, PyReadonlyArray2};
66
use pyo3::{pymodule, types::PyModule, PyResult, Python};
77

examples/simple-extension/README.md

Lines changed: 0 additions & 24 deletions
This file was deleted.

examples/simple-extension/noxfile.py

Lines changed: 0 additions & 8 deletions
This file was deleted.

examples/simple-extension/Cargo.toml renamed to examples/simple/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[package]
2-
name = "numpy-example"
2+
name = "rust-ext"
33
version = "0.1.0"
44
authors = ["Toshiki Teramura <[email protected]>", "Yuji Kanagawa <[email protected]>"]
55
edition = "2018"

examples/simple/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# simple extension
2+
3+
Here, we use [`maturin`][maturin] for building Python wheels and
4+
[`nox`][nox] for managing Python dependencies and virtualenvs.
5+
6+
Running `nox` inside this directory creates a virtualenv,
7+
installs Python dependencies and the extension into it
8+
and executes the tests from `tests/test_exp.py`.
9+
10+
By running
11+
```bash
12+
maturin develop
13+
```
14+
from inside a virtualenv, you can use the extension from
15+
the Python REPL:
16+
17+
```python
18+
>>> import numpy as np
19+
>>> import rust_ext
20+
>>> rust_ext.axpy(2.0, np.array([0.0, 1.0]), np.array([2.0, 3.0]))
21+
array([2., 5.])
22+
```
23+
24+
[maturin]: https://github.com/PyO3/maturin
25+
[nox]: https://github.com/theacodes/nox

examples/simple/noxfile.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import nox
2+
3+
4+
@nox.session
5+
def tests(session):
6+
session.install("pip", "numpy", "pytest")
7+
session.run("pip", "install", ".", "-v")
8+
session.run("pytest")

examples/simple-extension/src/lib.rs renamed to examples/simple/src/lib.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ use pyo3::{
88

99
#[pymodule]
1010
fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
11-
// immutable example
11+
// example using immutable borrows producing a new array
1212
fn axpy(a: f64, x: ArrayViewD<'_, f64>, y: ArrayViewD<'_, f64>) -> ArrayD<f64> {
1313
a * &x + &y
1414
}
1515

16-
// mutable example (no return)
16+
// example using a mutable borrow to modify an array in-place
1717
fn mult(a: f64, mut x: ArrayViewMutD<'_, f64>) {
1818
x *= a;
1919
}
2020

21-
// complex example
21+
// example using complex numbers
2222
fn conj(x: ArrayViewD<'_, Complex64>) -> ArrayD<Complex64> {
2323
x.map(|c| c.conj())
2424
}
@@ -56,8 +56,8 @@ fn rust_ext(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
5656
conj(x.as_array()).into_pyarray(py)
5757
}
5858

59+
// example of how to extract an array from a dictionary
5960
#[pyfn(m)]
60-
#[pyo3(name = "extract")]
6161
fn extract(d: &PyDict) -> f64 {
6262
let x = d
6363
.get_item("x")

examples/simple-extension/tests/test_ext.py renamed to examples/simple/tests/test_ext.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@ def test_axpy():
77
y = np.array([3.0, 3.0, 3.0])
88
z = axpy(3.0, x, y)
99
np.testing.assert_array_almost_equal(z, np.array([6.0, 9.0, 12.0]))
10-
x = np.array([1.0, 2.0, 3.0, 4.0])
11-
y = np.array([3.0, 3.0, 3.0, 3.0])
12-
z = axpy(3.0, x, y)
13-
np.testing.assert_array_almost_equal(z, np.array([6.0, 9.0, 12.0, 15.0]))
1410

1511

1612
def test_mult():
@@ -26,5 +22,5 @@ def test_conj():
2622

2723
def test_extract():
2824
x = np.arange(5.0)
29-
d = { "x": x }
25+
d = {"x": x}
3026
np.testing.assert_almost_equal(extract(d), 10.0)

0 commit comments

Comments
 (0)