2016-12-17 15:05:21 +00:00
|
|
|
// Copyright (c) 2016 Daniel Grunwald
|
2015-04-19 03:22:03 +00:00
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
|
|
|
// software and associated documentation files (the "Software"), to deal in the Software
|
|
|
|
// without restriction, including without limitation the rights to use, copy, modify, merge,
|
|
|
|
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
|
|
|
|
// to whom the Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in all copies or
|
|
|
|
// substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
|
|
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
|
|
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
|
|
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
|
|
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2016-03-05 23:03:17 +00:00
|
|
|
#![cfg_attr(feature="nightly", feature(
|
|
|
|
const_fn, // for GILProtected::new (#24111)
|
|
|
|
shared, // for std::ptr::Shared (#27730)
|
2017-01-20 22:14:29 +00:00
|
|
|
specialization, // for impl FromPyObject<'source> for Vec<...> (#31844)
|
2016-03-05 23:03:17 +00:00
|
|
|
))]
|
2016-03-04 23:13:38 +00:00
|
|
|
|
2015-06-27 21:49:53 +00:00
|
|
|
#![allow(unused_imports)] // because some imports are only necessary with python 2.x or 3.x
|
2015-01-05 16:05:53 +00:00
|
|
|
|
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
|
|
|
//!
|
2015-10-26 22:52:18 +00:00
|
|
|
//! The method `clone_ref()` (from trait `PyClone`) can be used to create additional
|
|
|
|
//! references to the same Python object.
|
|
|
|
//!
|
2016-01-29 03:13:39 +00:00
|
|
|
//! Because all Python objects potentially have multiple owners, the
|
2015-10-26 22:52:18 +00:00
|
|
|
//! 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
|
2015-10-26 22:52:18 +00:00
|
|
|
//! 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.
|
2015-10-26 22:52:18 +00:00
|
|
|
//! 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
|
|
|
//!
|
2015-10-26 22:52:18 +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
|
2015-10-26 22:52:18 +00:00
|
|
|
//! 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-05-13 05:43:17 +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
|
|
|
|
//! ```
|
2017-05-13 05:43:17 +00:00
|
|
|
//! extern crate pyo3;
|
2015-04-18 20:20:19 +00:00
|
|
|
//!
|
2017-05-13 05:43:17 +00:00
|
|
|
//! use pyo3::{Python, PyDict, PyResult};
|
2017-01-26 20:35:16 +00:00
|
|
|
//!
|
2015-04-18 20:20:19 +00:00
|
|
|
//! fn main() {
|
2015-07-27 18:56:59 +00:00
|
|
|
//! let gil = Python::acquire_gil();
|
2016-12-17 14:04:39 +00:00
|
|
|
//! hello(gil.python()).unwrap();
|
|
|
|
//! }
|
2017-01-26 20:35:16 +00:00
|
|
|
//!
|
2016-12-17 14:04:39 +00:00
|
|
|
//! fn hello(py: Python) -> PyResult<()> {
|
|
|
|
//! let sys = py.import("sys")?;
|
|
|
|
//! let version: String = sys.get(py, "version")?.extract(py)?;
|
2017-01-26 20:35:16 +00:00
|
|
|
//!
|
2016-12-17 14:04:39 +00:00
|
|
|
//! let locals = PyDict::new(py);
|
|
|
|
//! locals.set_item(py, "os", py.import("os")?)?;
|
|
|
|
//! let user: String = py.eval("os.getenv('USER') or os.getenv('USERNAME')", None, Some(&locals))?.extract(py)?;
|
2017-01-26 20:35:16 +00:00
|
|
|
//!
|
2015-07-27 18:56:59 +00:00
|
|
|
//! println!("Hello {}, I'm Python {}", user, version);
|
2016-12-17 14:04:39 +00:00
|
|
|
//! Ok(())
|
2015-04-18 20:20:19 +00:00
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
|
2015-01-05 16:05:53 +00:00
|
|
|
extern crate libc;
|
2015-05-19 21:32:32 +00:00
|
|
|
|
2017-05-14 19:52:30 +00:00
|
|
|
#[macro_use] pub extern crate pyo3cls;
|
|
|
|
pub use pyo3cls as cls;
|
|
|
|
|
2017-05-13 05:05:00 +00:00
|
|
|
pub mod ffi;
|
2015-01-05 16:05:53 +00:00
|
|
|
pub use ffi::Py_ssize_t;
|
|
|
|
pub use err::{PyErr, PyResult};
|
2015-01-05 16:02:30 +00:00
|
|
|
pub use objects::*;
|
2016-03-06 05:29:43 +00:00
|
|
|
pub use python::{Python, PythonObject, PythonObjectWithCheckedDowncast, PythonObjectDowncastError, PythonObjectWithTypeObject, PyClone, PyDrop};
|
2015-06-21 22:35:01 +00:00
|
|
|
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
|
2017-05-14 21:42:56 +00:00
|
|
|
pub use conversion::{FromPyObject, RefFromPyObject, ToPyObject, ToPyTuple};
|
2016-06-06 20:08:48 +00:00
|
|
|
pub use py_class::{CompareOp};
|
2015-01-04 20:37:43 +00:00
|
|
|
pub use objectprotocol::{ObjectProtocol};
|
2015-03-08 14:29:44 +00:00
|
|
|
|
2015-06-28 16:55:20 +00:00
|
|
|
#[allow(non_camel_case_types)]
|
|
|
|
pub type Py_hash_t = ffi::Py_hash_t;
|
|
|
|
|
2016-03-12 00:31:06 +00:00
|
|
|
use std::{ptr, mem};
|
2015-06-24 22:02:56 +00:00
|
|
|
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Constructs a `&'static CStr` literal.
|
2015-03-08 14:29:44 +00:00
|
|
|
macro_rules! cstr(
|
|
|
|
($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 _)
|
|
|
|
}
|
|
|
|
);
|
|
|
|
);
|
2015-01-05 16:05:53 +00:00
|
|
|
|
2016-03-06 12:33:57 +00:00
|
|
|
// AST coercion macros (https://danielkeep.github.io/tlborm/book/blk-ast-coercion.html)
|
|
|
|
#[macro_export] #[doc(hidden)]
|
|
|
|
macro_rules! py_coerce_expr { ($s:expr) => {$s} }
|
|
|
|
#[macro_export] #[doc(hidden)]
|
|
|
|
macro_rules! py_coerce_item { ($s:item) => {$s} }
|
|
|
|
|
2016-03-07 22:22:44 +00:00
|
|
|
#[macro_export] #[doc(hidden)]
|
|
|
|
macro_rules! py_replace_expr {
|
|
|
|
($_t:tt $sub:expr) => {$sub};
|
|
|
|
}
|
2016-03-06 12:33:57 +00:00
|
|
|
|
2016-05-08 19:25:09 +00:00
|
|
|
#[macro_export] #[doc(hidden)]
|
|
|
|
macro_rules! py_impl_to_py_object_for_python_object {
|
|
|
|
($T: ty) => (
|
|
|
|
/// Identity conversion: allows using existing `PyObject` instances where
|
|
|
|
/// `T: ToPyObject` is expected.
|
2017-05-14 21:42:56 +00:00
|
|
|
impl $crate::ToPyObject for $T where $T: $crate::PythonObject {
|
2016-05-08 19:25:09 +00:00
|
|
|
#[inline]
|
2017-05-14 21:42:56 +00:00
|
|
|
fn to_py_object(&self, py: $crate::Python) -> $crate::PyObject {
|
|
|
|
$crate::PyClone::clone_ref(self, py).into_object()
|
2016-05-08 19:25:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2017-05-14 21:42:56 +00:00
|
|
|
fn into_py_object(self, _py: $crate::Python) -> $crate::PyObject {
|
|
|
|
self.into_object()
|
2016-05-08 19:25:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn with_borrowed_ptr<F, R>(&self, _py: $crate::Python, f: F) -> R
|
|
|
|
where F: FnOnce(*mut $crate::_detail::ffi::PyObject) -> R
|
|
|
|
{
|
|
|
|
f($crate::PythonObject::as_object(self).as_ptr())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[macro_export] #[doc(hidden)]
|
|
|
|
macro_rules! py_impl_from_py_object_for_python_object {
|
|
|
|
($T:ty) => {
|
|
|
|
impl <'source> $crate::FromPyObject<'source> for $T {
|
|
|
|
#[inline]
|
|
|
|
fn extract(py: $crate::Python, obj: &'source $crate::PyObject) -> $crate::PyResult<$T> {
|
|
|
|
use $crate::PyClone;
|
|
|
|
Ok(try!(obj.clone_ref(py).cast_into::<$T>(py)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl <'source> $crate::FromPyObject<'source> for &'source $T {
|
|
|
|
#[inline]
|
|
|
|
fn extract(py: $crate::Python, obj: &'source $crate::PyObject) -> $crate::PyResult<&'source $T> {
|
|
|
|
Ok(try!(obj.cast_as::<$T>(py)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-15 01:55:04 +00:00
|
|
|
pub mod py_class;
|
2015-01-05 16:05:53 +00:00
|
|
|
mod python;
|
|
|
|
mod err;
|
2015-01-04 23:07:31 +00:00
|
|
|
mod conversion;
|
2015-01-05 16:02:30 +00:00
|
|
|
mod objects;
|
2015-01-04 20:37:43 +00:00
|
|
|
mod objectprotocol;
|
2015-01-05 16:05:53 +00:00
|
|
|
mod pythonrun;
|
2015-08-02 22:06:15 +00:00
|
|
|
pub mod argparse;
|
2015-06-25 21:58:57 +00:00
|
|
|
mod function;
|
2017-01-20 22:14:29 +00:00
|
|
|
pub mod buffer;
|
2017-05-15 01:55:04 +00:00
|
|
|
pub mod class;
|
|
|
|
pub use class::*;
|
2015-01-05 16:05:53 +00:00
|
|
|
|
2017-05-14 21:42:56 +00:00
|
|
|
// re-export for simplicity
|
|
|
|
pub use std::os::raw::*;
|
|
|
|
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Private re-exports for macros. Do not use.
|
2015-04-18 22:39:04 +00:00
|
|
|
#[doc(hidden)]
|
2015-04-18 18:17:25 +00:00
|
|
|
pub mod _detail {
|
2016-03-04 20:35:52 +00:00
|
|
|
pub mod ffi {
|
|
|
|
pub use ::ffi::*;
|
|
|
|
}
|
|
|
|
pub mod libc {
|
2017-05-13 05:05:00 +00:00
|
|
|
pub use std::os::raw::{c_char, c_void, c_int};
|
2016-03-04 20:35:52 +00:00
|
|
|
}
|
2016-03-12 16:58:50 +00:00
|
|
|
pub use err::{from_owned_ptr_or_panic, result_from_owned_ptr};
|
2016-05-05 05:31:14 +00:00
|
|
|
pub use function::{handle_callback, py_fn_impl, AbortOnDrop,
|
2017-05-15 01:55:04 +00:00
|
|
|
PyObjectCallbackConverter, PythonObjectCallbackConverter};
|
2015-04-18 18:17:25 +00:00
|
|
|
}
|
|
|
|
|
2015-06-27 20:45:35 +00:00
|
|
|
/// Expands to an `extern "C"` function that allows Python to load
|
|
|
|
/// the rust code as a Python extension module.
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2016-03-05 22:20:53 +00:00
|
|
|
/// Macro syntax: `py_module_initializer!($name, $py2_init, $py3_init, |$py, $m| $body)`
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2015-10-26 22:52:18 +00:00
|
|
|
/// 1. `name`: The module name as a Rust identifier.
|
2017-05-13 06:01:54 +00:00
|
|
|
/// 2. `py3_init`: "PyInit_" + $name. Necessary because macros can't use concat_idents!().
|
2016-03-05 22:20:53 +00:00
|
|
|
/// 4. A lambda of type `Fn(Python, &PyModule) -> PyResult<()>`.
|
2015-04-18 20:20:19 +00:00
|
|
|
/// This function will be called when the module is imported, and is responsible
|
|
|
|
/// for adding the module's members.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
/// ```
|
2017-05-13 05:43:17 +00:00
|
|
|
/// #[macro_use] extern crate pyo3;
|
|
|
|
/// use pyo3::{Python, PyResult, PyObject};
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2017-05-13 06:01:54 +00:00
|
|
|
/// py_module_init!(hello, PyInit_hello, |py, m| {
|
2016-12-17 20:17:11 +00:00
|
|
|
/// m.add(py, "__doc__", "Module documentation string")?;
|
|
|
|
/// m.add(py, "run", py_fn!(py, run()))?;
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Ok(())
|
|
|
|
/// });
|
2015-07-27 18:56:59 +00:00
|
|
|
///
|
2015-10-25 16:55:29 +00:00
|
|
|
/// fn run(py: Python) -> PyResult<PyObject> {
|
2015-04-18 20:20:19 +00:00
|
|
|
/// println!("Rust says: Hello Python!");
|
|
|
|
/// Ok(py.None())
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2016-12-17 20:17:11 +00:00
|
|
|
///
|
2017-05-13 05:43:17 +00:00
|
|
|
/// In your `Cargo.toml`, use the `extension-module` feature for the `pyo3` dependency:
|
2016-12-17 20:17:11 +00:00
|
|
|
/// ```cargo
|
2017-05-13 05:43:17 +00:00
|
|
|
/// [dependencies.pyo3]
|
2016-12-17 20:17:11 +00:00
|
|
|
/// version = "*"
|
|
|
|
/// features = ["extension-module"]
|
|
|
|
/// ```
|
|
|
|
/// The full example project can be found at:
|
2017-05-13 05:43:17 +00:00
|
|
|
/// https://github.com/PyO3/setuptools-rust/tree/master/example/extensions
|
2017-01-26 20:35:16 +00:00
|
|
|
///
|
2016-12-17 20:17:11 +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:
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
|
|
|
/// ```bash
|
2016-12-17 20:17:11 +00:00
|
|
|
/// cp ./target/debug/libhello.so ./hello.so
|
2015-04-18 20:20:19 +00:00
|
|
|
/// ```
|
2016-12-17 20:17:11 +00:00
|
|
|
/// (Note: on Mac OS you will have to rename `libhello.dynlib` to `libhello.so`)
|
|
|
|
///
|
|
|
|
/// The extension module can then be imported into Python:
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
|
|
|
/// ```python
|
2016-12-17 20:17:11 +00:00
|
|
|
/// >>> import hello
|
|
|
|
/// >>> hello.run()
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Rust says: Hello Python!
|
|
|
|
/// ```
|
2015-07-27 18:56:59 +00:00
|
|
|
///
|
2015-01-12 02:00:34 +00:00
|
|
|
#[macro_export]
|
2017-05-13 06:01:54 +00:00
|
|
|
macro_rules! py_module_init {
|
2017-05-13 05:05:00 +00:00
|
|
|
($name: ident, $py3: ident, |$py_id: ident, $m_id: ident| $body: expr) => {
|
2016-03-05 22:20:53 +00:00
|
|
|
#[no_mangle]
|
2015-05-24 18:06:08 +00:00
|
|
|
#[allow(non_snake_case)]
|
2017-05-13 05:05:00 +00:00
|
|
|
pub unsafe extern "C" fn $py3() -> *mut $crate::ffi::PyObject {
|
2015-06-24 22:02:56 +00:00
|
|
|
// Nest init function so that $body isn't in unsafe context
|
2015-10-25 16:55:29 +00:00
|
|
|
fn init($py_id: $crate::Python, $m_id: &$crate::PyModule) -> $crate::PyResult<()> {
|
2015-06-24 22:02:56 +00:00
|
|
|
$body
|
|
|
|
}
|
2017-05-13 05:05:00 +00:00
|
|
|
static mut MODULE_DEF: $crate::ffi::PyModuleDef = $crate::_detail::ffi::PyModuleDef_INIT;
|
2015-05-24 18:06:08 +00:00
|
|
|
// We can't convert &'static str to *const c_char within a static initializer,
|
|
|
|
// so we'll do it here in the module initialization:
|
2016-11-12 02:50:18 +00:00
|
|
|
MODULE_DEF.m_name = concat!(stringify!($name), "\0").as_ptr() as *const _;
|
2017-05-13 06:01:54 +00:00
|
|
|
$crate::py_module_init_impl(&mut MODULE_DEF, init)
|
2015-06-24 22:02:56 +00:00
|
|
|
}
|
2016-03-05 22:20:53 +00:00
|
|
|
}
|
2015-06-24 22:02:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
2017-05-13 06:01:54 +00:00
|
|
|
pub unsafe fn py_module_init_impl(
|
2015-06-24 22:02:56 +00:00
|
|
|
def: *mut ffi::PyModuleDef,
|
2017-05-13 06:01:54 +00:00
|
|
|
init: fn(Python, &PyModule) -> PyResult<()>) -> *mut ffi::PyObject
|
|
|
|
{
|
|
|
|
let guard = function::AbortOnDrop("py_module_init");
|
2016-03-12 00:31:06 +00:00
|
|
|
let py = Python::assume_gil_acquired();
|
|
|
|
ffi::PyEval_InitThreads();
|
|
|
|
let module = ffi::PyModule_Create(def);
|
|
|
|
if module.is_null() {
|
|
|
|
mem::forget(guard);
|
|
|
|
return module;
|
|
|
|
}
|
2015-06-24 22:02:56 +00:00
|
|
|
|
2016-03-12 00:31:06 +00:00
|
|
|
let module = match PyObject::from_owned_ptr(py, module).cast_into::<PyModule>(py) {
|
|
|
|
Ok(m) => m,
|
|
|
|
Err(e) => {
|
|
|
|
PyErr::from(e).restore(py);
|
|
|
|
mem::forget(guard);
|
|
|
|
return ptr::null_mut();
|
2015-05-24 18:06:08 +00:00
|
|
|
}
|
2016-03-12 00:31:06 +00:00
|
|
|
};
|
|
|
|
let ret = match init(py, &module) {
|
|
|
|
Ok(()) => module.into_object().steal_ptr(),
|
|
|
|
Err(e) => {
|
|
|
|
e.restore(py);
|
|
|
|
ptr::null_mut()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
mem::forget(guard);
|
|
|
|
ret
|
2015-01-12 02:00:34 +00:00
|
|
|
}
|