pyo3/src/lib.rs

227 lines
6.8 KiB
Rust
Raw Normal View History

#![feature(specialization, proc_macro, try_from, fn_must_use, concat_idents)]
2016-03-06 12:33:57 +00:00
2015-06-27 20:45:35 +00:00
//! Rust bindings to the Python interpreter.
2015-04-18 20:20:19 +00:00
//!
2015-04-18 22:39:04 +00:00
//! # Ownership and Lifetimes
2015-06-27 20:45:35 +00:00
//! In Python, all objects are implicitly reference counted.
//! In rust, we will use the `PyObject` type to represent a reference to a Python object.
2015-04-18 22:39:04 +00:00
//!
2016-01-29 03:13:39 +00:00
//! Because all Python objects potentially have multiple owners, the
//! concept of Rust mutability does not apply to Python objects.
2015-06-27 20:45:35 +00:00
//! As a result, this API will allow mutating Python objects even if they are not stored
//! in a mutable Rust variable.
2015-04-18 22:39:04 +00:00
//!
2015-06-27 20:45:35 +00:00
//! The Python interpreter uses a global interpreter lock (GIL)
2015-04-18 22:39:04 +00:00
//! to ensure thread-safety.
//! This API uses a zero-sized `struct Python<'p>` as a token to indicate
//! that a function can assume that the GIL is held.
2015-04-18 22:39:04 +00:00
//!
//! You obtain a `Python` instance by acquiring the GIL,
//! and have to pass it into all operations that call into the Python runtime.
2015-04-18 22:39:04 +00:00
//!
//! # Error Handling
//! The vast majority of operations in this library will return `PyResult<...>`.
//! This is an alias for the type `Result<..., PyErr>`.
2015-04-18 22:39:04 +00:00
//!
2017-06-11 15:46:23 +00:00
//! A `PyErr` represents a Python exception. Errors within the `PyO3` library are
2015-06-27 20:45:35 +00:00
//! also exposed as Python exceptions.
2015-04-18 22:39:04 +00:00
//!
2015-04-18 20:20:19 +00:00
//! # Example
//!
//! ```rust
2017-05-13 05:43:17 +00:00
//! extern crate pyo3;
2015-04-18 20:20:19 +00:00
//!
//! use pyo3::{Python, PyDict, PyResult, ObjectProtocol};
//!
2015-04-18 20:20:19 +00:00
//! fn main() {
//! let gil = Python::acquire_gil();
//! hello(gil.python()).unwrap();
//! }
//!
//! fn hello(py: Python) -> PyResult<()> {
//! let sys = py.import("sys")?;
//! let version: String = sys.get("version")?.extract()?;
//!
//! let locals = PyDict::new(py);
2017-06-21 21:08:16 +00:00
//! locals.set_item("os", py.import("os")?)?;
//! let user: String = py.eval("os.getenv('USER') or os.getenv('USERNAME')", None, Some(locals))?.extract()?;
//!
//! println!("Hello {}, I'm Python {}", user, version);
//! Ok(())
2015-04-18 20:20:19 +00:00
//! }
//! ```
2017-06-11 23:35:24 +00:00
//!
2017-06-15 18:13:58 +00:00
//! # Python extension
//!
//! To allow Python to load the rust code as a Python extension
2018-05-01 18:41:35 +00:00
//! module, you need provide initialization function and annotate it with `#[pymodinit(name)]`.
//! `pymodinit` expands to an `extern "C"` function.
2017-06-11 23:35:24 +00:00
//!
2018-05-01 18:41:35 +00:00
//! Macro syntax: `#[pymodinit(name)]`
2017-06-11 23:35:24 +00:00
//!
//! 1. `name`: The module name as a Rust identifier
//! 2. Decorate init function `Fn(Python, &PyModule) -> PyResult<()>`.
//! This function will be called when the module is imported, and is responsible
//! for adding the module's members.
//!
//! To creates a Python callable object that invokes a Rust function, specify rust
2017-06-15 21:20:30 +00:00
//! function and decorate it with `#[pyfn()]` attribute. `pyfn()` accepts three parameters.
//!
//! 1. `m`: The module name.
2017-06-15 21:20:30 +00:00
//! 2. name of function visible to Python code.
//! 3. comma separated arguments, i.e. param="None", "*", param3="55"
//!
//!
2017-06-11 23:35:24 +00:00
//! # Example
//!
//! ```rust
2017-06-18 16:28:21 +00:00
//! #![feature(proc_macro, specialization)]
//!
2017-06-14 21:42:05 +00:00
//! extern crate pyo3;
//! use pyo3::{py, Python, PyResult, PyModule, PyString};
2017-06-11 23:35:24 +00:00
//!
2018-05-01 18:41:35 +00:00
//! use pyo3::py::modinit as pymodinit;
//!
2017-06-15 21:20:30 +00:00
//! // add bindings to the generated python module
//! // N.B: names: "libhello" must be the name of the `.so` or `.pyd` file
2017-06-19 21:05:14 +00:00
//!
//! /// Module documentation string
2018-05-01 18:41:35 +00:00
//! #[pymodinit(hello)]
2017-06-12 06:51:53 +00:00
//! fn init_module(py: Python, m: &PyModule) -> PyResult<()> {
//!
2017-06-15 21:20:30 +00:00
//! // pyo3 aware function. All of our python interface could be declared
//! // in a separate module.
//! // Note that the `#[pyfn()]` annotation automatically converts the arguments from
//! // Python objects to Rust values; and the Rust return value back into a Python object.
//! #[pyfn(m, "run_rust_func")]
2017-07-26 21:28:04 +00:00
//! fn run(name: &PyString) -> PyResult<()> {
//! println!("Rust says: Hello {} of Python!", name);
2017-06-21 21:08:16 +00:00
//! Ok(())
//! }
//!
2017-06-11 23:35:24 +00:00
//! Ok(())
//! }
//!
//! # fn main() {}
//! ```
//!
//! In your `Cargo.toml`, use the `extension-module` feature for the `pyo3` dependency:
2017-06-15 16:11:19 +00:00
//!
2017-06-11 23:35:24 +00:00
//! ```cargo
//! [dependencies.pyo3]
//! version = "*"
//! features = ["extension-module"]
//! ```
//!
//! The full example project can be found at:
2017-06-15 21:30:11 +00:00
//! <https://github.com/PyO3/setuptools-rust/tree/master/example/>
2017-06-11 23:35:24 +00:00
//!
//! Rust will compile the code into a file named `libhello.so`, but we have to
//! rename the file in order to use it with Python:
//!
//! ```bash
//! cp ./target/debug/libhello.so ./hello.so
//! ```
//!
//! (Note: on macOS you will have to rename `libhello.dynlib` to `libhello.so`.
2018-01-19 18:02:36 +00:00
//! To build on macOS, use `-C link-arg=-undefined -C link-arg=dynamic_lookup`
//! is required to build the library.
//! `setuptools-rust` includes this by default.
//! See [examples/word-count](https://github.com/PyO3/pyo3/tree/master/examples/word-count).)
2017-06-11 23:35:24 +00:00
//!
//! The extension module can then be imported into Python:
//!
2018-02-21 17:23:58 +00:00
//! ```python,ignore
2017-06-11 23:35:24 +00:00
//! >>> import hello
//! >>> hello.run_rust_func("test")
2017-06-11 23:35:24 +00:00
//! Rust says: Hello Python!
//! ```
2015-04-18 20:20:19 +00:00
2015-01-05 16:05:53 +00:00
extern crate libc;
2017-07-09 06:08:57 +00:00
extern crate spin;
2017-06-11 23:35:24 +00:00
extern crate pyo3cls;
2017-06-06 03:25:00 +00:00
#[macro_use] extern crate log;
2017-06-11 23:35:24 +00:00
#[cfg(not(Py_3))]
mod ffi2;
2017-06-11 23:47:27 +00:00
#[cfg(Py_3)]
mod ffi3;
2017-06-24 08:47:36 +00:00
/// Rust FFI declarations for Python
2017-06-11 23:35:24 +00:00
pub mod ffi {
2017-06-11 23:47:27 +00:00
#[cfg(not(Py_3))]
2017-06-11 23:35:24 +00:00
pub use ffi2::*;
2017-06-11 23:47:27 +00:00
#[cfg(Py_3)]
pub use ffi3::*;
2017-06-11 23:35:24 +00:00
}
2017-07-26 17:47:17 +00:00
pub use err::{PyErr, PyErrValue, PyResult, PyDowncastError, PyErrArguments};
2015-01-05 16:02:30 +00:00
pub use objects::*;
2017-05-28 15:57:34 +00:00
pub use objectprotocol::ObjectProtocol;
2017-07-13 20:05:50 +00:00
pub use object::PyObject;
pub use noargs::NoArgs;
2017-08-08 07:27:33 +00:00
pub use typeob::{PyTypeInfo, PyRawObject, PyObjectAlloc};
2017-08-03 22:55:23 +00:00
pub use python::{Python, ToPyPointer, IntoPyPointer, IntoPyDictPointer};
2017-07-20 21:21:57 +00:00
pub use pythonrun::{GILGuard, GILPool, prepare_freethreaded_python, prepare_pyo3_library};
2017-06-22 08:16:22 +00:00
pub use instance::{PyToken, PyObjectWithToken, AsPyRef, Py, PyNativeType};
pub use conversion::{FromPyObject, PyTryFrom, PyTryInto,
ToPyObject, ToBorrowedObject, IntoPyObject, IntoPyTuple,
ReturnTypeIntoPyResult};
2017-05-25 03:31:51 +00:00
pub mod class;
pub use class::*;
2015-03-08 14:29:44 +00:00
2017-06-24 08:47:36 +00:00
/// Procedural macros
2017-05-18 18:15:06 +00:00
pub mod py {
pub use pyo3cls::{proto, class, methods, function};
2017-06-11 23:35:24 +00:00
#[cfg(Py_3)]
pub use pyo3cls::mod3init as modinit;
#[cfg(not(Py_3))]
pub use pyo3cls::mod2init as modinit;
2017-05-18 18:15:06 +00:00
}
2015-04-18 20:20:19 +00:00
/// Constructs a `&'static CStr` literal.
macro_rules! cstr {
2015-03-08 14:29:44 +00:00
($s: tt) => (
// TODO: verify that $s is a string literal without nuls
unsafe {
::std::ffi::CStr::from_ptr(concat!($s, "\0").as_ptr() as *const _)
}
);
}
/// Registers a function annotated with `#[function]` in module.
/// The first parameter is the module, the second the name of the function and the third is an
/// instance of `Python`.
#[macro_export]
macro_rules! add_function_to_module(
($modname:expr, $function_name:ident, $python:expr) => {
concat_idents!(__pyo3_add_to_module_, $function_name)($modname, $python);
};
2015-03-08 14:29:44 +00:00
);
2015-01-05 16:05:53 +00:00
2017-06-15 18:13:58 +00:00
mod python;
2015-01-05 16:05:53 +00:00
mod err;
mod conversion;
2017-06-22 08:16:22 +00:00
mod instance;
2017-07-13 20:05:50 +00:00
mod object;
2015-01-05 16:02:30 +00:00
mod objects;
2015-01-04 20:37:43 +00:00
mod objectprotocol;
mod noargs;
2015-01-05 16:05:53 +00:00
mod pythonrun;
2017-07-18 17:13:50 +00:00
#[doc(hidden)]
2017-05-25 05:43:07 +00:00
pub mod callback;
pub mod typeob;
2017-06-24 14:30:46 +00:00
#[doc(hidden)]
pub mod argparse;
2017-05-31 08:07:33 +00:00
pub mod buffer;
2017-06-09 21:27:37 +00:00
pub mod freelist;
2017-07-31 17:42:55 +00:00
pub mod prelude;
2015-01-05 16:05:53 +00:00
2017-05-14 21:42:56 +00:00
// re-export for simplicity
2017-06-15 16:11:19 +00:00
#[doc(hidden)]
2017-05-14 21:42:56 +00:00
pub use std::os::raw::*;