Merge branch 'master' into pyany

This commit is contained in:
konstin 2019-03-18 01:00:26 +01:00 committed by GitHub
commit 59a9d4fd9f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
34 changed files with 509 additions and 398 deletions

11
.github/pull_request_template.md vendored Normal file
View file

@ -0,0 +1,11 @@
Thank you for contributing to pyo3!
Here are some things you should check for submitting your pull request:
- Run `cargo fmt` (This is checked by travis ci)
- Run `cargo clippy` and check there are no hard errors (There are a bunch of existing warnings; This is also checked by travis)
- If applicable, add an entry in the changelog.
- If applicable, add documentation to all new items and extend the guide.
- If applicable, add tests for all new or fixed functions
You might want to run `tox` (`pip install tox`) locally to check compatibility with all supported python versions. If you're using linux or mac you might find the Makefile helpful for testing.

View file

@ -13,7 +13,7 @@ matrix:
env: FEATURES=python2
- name: Python 3.5
python: "3.5"
env: FEATURES=python3
env: FEATURES="python3 test-doc"
- name: Python 3.6
python: "3.6"
env: FEATURES=python3

View file

@ -48,6 +48,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Fixed
* A soudness hole where every instances of a `#[pyclass]` struct was considered to be part of a python object, even though you can create instances that are not part of the python heap. This was fixed through `PyRef` and `PyRefMut`.
* Fix kwargs support in [#328].
* Add full support for `__dict__` in [#403].
## [0.5.3] - 2019-01-04

View file

@ -55,6 +55,9 @@ extension-module = []
# are welcome.
# abi3 = []
# Use this feature to test the examples in the user guide
test-doc = []
[workspace]
members = [
"pyo3cls",

View file

@ -15,7 +15,7 @@ A comparison with rust-cpython can be found [in the guide](https://pyo3.rs/maste
## Usage
Pyo3 supports python 2.7 as well as python 3.5 and up. The minimum required rust version is 1.34.0-nightly 2019-02-06.
PyO3 supports python 2.7 as well as python 3.5 and up. The minimum required rust version is 1.34.0-nightly 2019-02-06.
You can either write a native python module in rust or use python from a rust binary.
@ -29,7 +29,7 @@ sudo apt install python3-dev python-dev
## Using rust from python
Pyo3 can be used to generate a native python module.
PyO3 can be used to generate a native python module.
**`Cargo.toml`**
@ -51,6 +51,9 @@ features = ["extension-module"]
**`src/lib.rs`**
```rust
// Not required when using Rust 2018
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
@ -95,6 +98,9 @@ pyo3 = "0.6.0-alpha.4"
Example program displaying the value of `sys.version`:
```rust
// Not required when using Rust 2018
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::types::PyDict;

View file

@ -1,6 +1,6 @@
#!/bin/sh
set -ex
set -e
### Setup Rust toolchain #######################################################

View file

@ -1,6 +1,7 @@
#!/bin/bash
set -ex
cargo clean
cargo test --features "$FEATURES num-complex"
if [ $TRAVIS_JOB_NAME = 'Minimum nightly' ]; then
cargo fmt --all -- --check

View file

@ -8,5 +8,6 @@
- [Python Class](class.md)
- [Parallelism](parallelism.md)
- [Debugging](debugging.md)
- [Advanced Topics](advanced.md)
- [Building and Distribution](building-and-distribution.md)
- [Appendix: Pyo3 and rust-cpython](rust-cpython.md)

7
guide/src/advanced.md Normal file
View file

@ -0,0 +1,7 @@
# Advanced topics
## ffi
PyO3 exposes much of python's C api through the `ffi`.
The C api is naturally unsafe and requires you to manage reference counts, errors and specific invariants yourself. Please refer to the [C API Reference Manual](https://docs.python.org/3/c-api/) and [The Rustonomicon](https://doc.rust-lang.org/nightly/nomicon/ffi.html) before using any function from that api.

View file

@ -2,13 +2,13 @@
## Python version
pyo3 uses a build script to determine the python version and set the correct linker arguments. By default it uses the `python3` executable. With the `python2` feature it uses the `python2` executable. You can override the python interpreter by setting `PYTHON_SYS_EXECUTABLE`.
PyO3 uses a build script to determine the python version and set the correct linker arguments. By default it uses the `python3` executable. With the `python2` feature it uses the `python2` executable. You can override the python interpreter by setting `PYTHON_SYS_EXECUTABLE`.
## Linking
Different linker arguments must be set for libraries/extension modules and binaries, which includes both standalone binaries and tests. (More specifically, binaries must be told where to find libpython and libraries must not link to libpython for [manylinux](https://www.python.org/dev/peps/pep-0513/) compliance).
Since pyo3's build script can't know whether you're building a binary or a library, you have to activate the `extension-module` feature to get the build options for a library, or it'll default to binary.
Since PyO3's build script can't know whether you're building a binary or a library, you have to activate the `extension-module` feature to get the build options for a library, or it'll default to binary.
If you have e.g. a library crate and a profiling crate alongside, you need to use optional features. E.g. you put the following in the library crate:
@ -40,7 +40,7 @@ There are two ways to distribute your module as python package: The old [setupto
## Cross Compiling
Cross compiling Pyo3 modules is relatively straightforward and requires a few pieces of software:
Cross compiling PyO3 modules is relatively straightforward and requires a few pieces of software:
* A toolchain for your target.
* The appropriate options in your Cargo `.config` for the platform you're targeting and the toolchain you are using.

View file

@ -2,9 +2,11 @@
## Define new class
To define python custom class, rust struct needs to be annotated with `#[pyclass]` attribute.
To define a custom python class, a rust struct needs to be annotated with the
`#[pyclass]` attribute.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
#[pyclass]
@ -19,12 +21,12 @@ The above example generates implementations for `PyTypeInfo` and `PyTypeObject`
## Get Python objects from `pyclass`
You can use `pyclass`es like normal rust structs.
However, if instantiate noramlly, you can't treat `pyclass`es as Python objects.
However, if instantiated normally, you can't treat `pyclass`es as Python objects.
To get a Python object which includes `pyclass`, we have to use some special methods.
### `PyRef`
`PyRef` is a special reference, which ensures that the reffrered struct is a part of
`PyRef` is a special reference, which ensures that the referred struct is a part of
a Python object, and you are also holding the GIL.
You can get an instance of `PyRef` by `PyRef::new`, which does 3 things:
@ -34,6 +36,7 @@ You can get an instance of `PyRef` by `PyRef::new`, which does 3 things:
You can use `PyRef` just like `&T`, because it implements `Deref<Target=T>`.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# use pyo3::types::PyDict;
#[pyclass]
@ -53,6 +56,7 @@ dict.set_item("obj", obj).unwrap();
### `PyRefMut`
`PyRefMut` is a mutable version of `PyRef`.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
@ -70,6 +74,7 @@ obj.num = 5;
You can use it to avoid lifetime problems.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
@ -99,8 +104,7 @@ python object that can be collected, the `PyGCProtocol` trait has to be implemen
* `weakref` - adds support for python weak references
* `extends=BaseType` - use a custom base class. The base BaseType must implement `PyTypeInfo`.
* `subclass` - Allows Python classes to inherit from this class
* `dict` - adds `__dict__` support, the instances of this type have a dictionary containing instance variables. (Incomplete, see [#123](https://github.com/PyO3/pyo3/issues/123))
* `dict` - adds `__dict__` support, the instances of this type have a dictionary containing instance variables.
## Constructor
@ -109,6 +113,7 @@ To declare a constructor, you need to define a class method and annotate it with
attribute. Only the python `__new__` method can be specified, `__init__` is not available.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# use pyo3::PyRawObject;
#[pyclass]
@ -149,7 +154,8 @@ By default `PyObject` is used as default base class. To override default base cl
`new` method accepts `PyRawObject` object. `obj` instance must be initialized
with value of custom class struct. Subclass must call parent's `new` method.
```rust
```rust,ignore
# extern crate pyo3;
# use pyo3::prelude::*;
# use pyo3::PyRawObject;
#[pyclass]
@ -183,7 +189,7 @@ impl SubClass {
}
fn method2(&self) -> PyResult<()> {
self.get_base().method()
self.get_base().method()
}
}
```
@ -199,6 +205,7 @@ Descriptor methods can be defined in
attributes. i.e.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -219,10 +226,11 @@ Getter or setter function's name is used as property name by default. There are
ways how to override name.
If function name starts with `get_` or `set_` for getter or setter respectively.
Descriptor name becomes function name with prefix removed. This is useful in case os
Descriptor name becomes function name with prefix removed. This is useful in case of
rust's special keywords like `type`.
```rust
```rust,ignore
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -248,9 +256,10 @@ impl MyClass {
In this case property `num` is defined. And it is available from python code as `self.num`.
Also both `#[getter]` and `#[setter]` attributes accepts one parameter.
If parameter is specified, it is used and property name. i.e.
If this parameter is specified, it is used as a property name. i.e.
```rust
```rust,ignore
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -273,11 +282,12 @@ impl MyClass {
}
```
In this case property `number` is defined. And it is available from python code as `self.number`.
In this case the property `number` is defined and is available from python code as `self.number`.
For simple cases you can also define getters and setters in your Rust struct field definition, for example:
```rust
```rust,ignore
# extern crate pyo3;
# use pyo3::prelude::*;
#[pyclass]
struct MyClass {
@ -290,12 +300,12 @@ Then it is available from Python code as `self.num`.
## Instance methods
To define python compatible method, `impl` block for struct has to be annotated
with `#[pymethods]` attribute. `pyo3` library generates python compatible
wrappers for all functions in this block with some variations, like descriptors,
class method static methods, etc.
To define a python compatible method, `impl` block for struct has to be annotated with the
`#[pymethods]` attribute. PyO3 generates python compatible wrappers for all functions in this
block with some variations, like descriptors, class method static methods, etc.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -323,6 +333,7 @@ The return type must be `PyResult<T>` for some `T` that implements `IntoPyObject
get injected by method wrapper. i.e
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -342,10 +353,11 @@ From python perspective `method2`, in above example, does not accept any argumen
## Class methods
To specify class method for custom class, method needs to be annotated
with`#[classmethod]` attribute.
To specify a class method for a custom class, the method needs to be annotated
with the `#[classmethod]` attribute.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# use pyo3::types::PyType;
# #[pyclass]
@ -373,11 +385,12 @@ Declares a class method callable from Python.
## Static methods
To specify class method for custom class, method needs to be annotated
with `#[staticmethod]` attribute. The return type must be `PyResult<T>`
for some `T` that implements `IntoPyObject`.
To specify a static method for a custom class, method needs to be annotated with
`#[staticmethod]` attribute. The return type must be `PyResult<T>` for some `T` that implements
`IntoPyObject`.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {
@ -396,10 +409,11 @@ impl MyClass {
## Callable object
To specify custom `__call__` method for custom class, call method needs to be annotated
with `#[call]` attribute. Arguments of the method are specified same as for instance method.
To specify a custom `__call__` method for a custom class, call methods need to be annotated with
the `#[call]` attribute. Arguments of the method are specified same as for instance method.
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
use pyo3::types::PyTuple;
# #[pyclass]
@ -421,14 +435,13 @@ impl MyClass {
## Method arguments
By default pyo3 library uses function signature to determine which arguments are required.
Then it scans incoming `args` parameter and then incoming `kwargs` parameter. If it can not
find all required parameters, it raises `TypeError` exception.
It is possible to override default behavior with `#[args(...)]` attribute. `args` attribute
accept comma separated list of parameters in form `attr_name="default value"`. Each parameter
has to match method parameter by name.
By default PyO3 uses function signatures to determine which arguments are required. Then it scans
incoming `args` parameter and then incoming `kwargs` parameter. If it can not find all required
parameters, it raises a `TypeError` exception. It is possible to override the default behavior
with `#[args(...)]` attribute. `args` attribute accepts a comma separated list of parameters in
form of `attr_name="default value"`. Each parameter has to match the method parameter by name.
Each parameter could one of following type:
Each parameter could be one of following type:
* "\*": var arguments separator, each parameter defined after "*" is keyword only parameters.
corresponds to python's `def meth(*, arg1.., arg2=..)`
@ -438,11 +451,12 @@ Each parameter could one of following type:
Type of `kwargs` parameter has to be `Option<&PyDict>`.
* arg="Value": arguments with default value. corresponds to python's `def meth(arg=Value)`.
if `arg` argument is defined after var arguments it is treated as keyword argument.
Note that `Value` has to be valid rust code, pyo3 just inserts it into generated
Note that `Value` has to be valid rust code, PyO3 just inserts it into generated
code unmodified.
Example:
```rust
# extern crate pyo3;
# use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#
@ -464,11 +478,10 @@ impl MyClass {
## Class customizations
Python object model defines several protocols for different object behavior,
like sequence, mapping or number protocols. pyo3 library defines separate trait for each
of them. To provide specific python object behavior you need to implement specific trait
for your struct. Important note, each protocol implementation block has to be annotated
with `#[pyproto]` attribute.
Python's object model defines several protocols for different object behavior, like sequence,
mapping or number protocols. PyO3 defines separate traits for each of them. To provide specific
python object behavior you need to implement the specific trait for your struct. Important note,
each protocol implementation block has to be annotated with `#[pyproto]` attribute.
### Basic object customization
@ -527,7 +540,7 @@ Each methods corresponds to python's `self.attr`, `self.attr = value` and `del s
* `fn __bool__(&self) -> PyResult<bool>`
Determines the "truthyness" of the object.
Determines the "truthiness" of the object.
This method works for both python 3 and python 2,
even on Python 2.7 where the Python spelling was `__nonzero__`.
@ -545,6 +558,8 @@ These correspond to the slots `tp_traverse` and `tp_clear` in the Python C API.
as every cycle must contain at least one mutable reference.
Example:
```rust
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::PyTraverseError;
use pyo3::gc::{PyGCProtocol, PyVisit};
@ -574,9 +589,9 @@ impl PyGCProtocol for ClassWithGCSupport {
}
```
Special protocol trait implementation has to be annotated with `#[pyproto]` attribute.
Special protocol trait implementations have to be annotated with the `#[pyproto]` attribute.
It is also possible to enable gc for custom class using `gc` parameter for `class` annotation.
It is also possible to enable GC for custom class using `gc` parameter for `class` annotation.
i.e. `#[pyclass(gc)]`. In that case instances of custom class participate in python garbage
collector, and it is possible to track them with `gc` module methods.
@ -585,14 +600,16 @@ collector, and it is possible to track them with `gc` module methods.
Iterators can be defined using the
[`PyIterProtocol`](https://docs.rs/pyo3/0.6.0-alpha.4/class/iter/trait.PyIterProtocol.html) trait.
It includes two methods `__iter__` and `__next__`:
* `fn __iter__(&mut self) -> PyResult<impl IntoPyObject>`
* `fn __next__(&mut self) -> PyResult<Option<impl IntoPyObject>>`
* `fn __iter__(slf: PyRefMut<Self>) -> PyResult<impl IntoPyObject>`
* `fn __next__(slf: PyRefMut<Self>) -> PyResult<Option<impl IntoPyObject>>`
Returning `Ok(None)` from `__next__` indicates that that there are no further items.
Example:
```rust
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::PyIterProtocol;
@ -618,6 +635,10 @@ TODO: Which traits to implement (basically `PyTypeCreate: PyObjectAlloc + PyType
## How methods are implemented
Users should be able to define a `#[pyclass]` with or without `#[pymethods]`, while pyo3 needs a trait with a function that returns all methods. Since it's impossible make the code generation in pyclass dependent on whether there is an impl block, we'd need to make to implement the trait on `#[pyclass]` and override the implementation in `#[pymethods]`, which is to my best knowledge only possible with the specialization feature, which is can't be used on stable.
Users should be able to define a `#[pyclass]` with or without `#[pymethods]`, while PyO3 needs a
trait with a function that returns all methods. Since it's impossible to make the code generation in
pyclass dependent on whether there is an impl block, we'd need to implement the trait on
`#[pyclass]` and override the implementation in `#[pymethods]`, which is to the best of my knowledge
only possible with the specialization feature, which can't be used on stable.
To escape this we use [inventory](https://github.com/dtolnay/inventory), which allows us to collect `impl`s from arbitrary source code by exploiting some binary trick. See [inventory: how it works](https://github.com/dtolnay/inventory#how-it-works) and `pyo3_derive_backend::py_class::impl_inventory` for more details.

View file

@ -1,6 +1,6 @@
# Type Conversions
`PyO3` provides some handy traits to convert between Python types and Rust types.
PyO3 provides some handy traits to convert between Python types and Rust types.
## `.extract()`
@ -24,6 +24,7 @@ provides two methods:
Both methods accept `args` and `kwargs` arguments.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
@ -61,6 +62,7 @@ fn main() {
[`IntoPyDict`][IntoPyDict] trait to convert other dict-like containers, e.g. `HashMap`, `BTreeMap` as well as tuples with up to 10 elements and `Vec`s where each element is a two element tuple.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict};
use std::collections::HashMap;
@ -102,7 +104,7 @@ fn main() {
## `IntoPy<T>`
Many conversions in pyo3 can't use `std::convert::Into` because they need a gil token. That's why the `IntoPy<T>` trait offers an `into_py` methods that works just like `into` except for taking a `Python<'_>` as argument.
Many conversions in PyO3 can't use `std::convert::Into` because they need a gil token. That's why the `IntoPy<T>` trait offers an `into_py` methods that works just like `into` except for taking a `Python<'_>` as argument.
Eventually, traits such as `IntoPyObject` will be replaces by this trait and a `FromPy` trait will be added that will implement `IntoPy`, just like with `From` and `Into`.

View file

@ -2,7 +2,7 @@
## Macros
Pyo3's attributes, `#[pyclass]`, `#[pymodule]`, etc. are [procedural macros](https://doc.rust-lang.org/unstable-book/language-features/proc-macro.html), which means that rewrite the source of the annotated item. You can view the generated source with the following command, which also expands a few other things:
PyO3's attributes, `#[pyclass]`, `#[pymodule]`, etc. are [procedural macros](https://doc.rust-lang.org/unstable-book/language-features/proc-macro.html), which means that rewrite the source of the annotated item. You can view the generated source with the following command, which also expands a few other things:
```bash
cargo rustc --profile=check -- -Z unstable-options --pretty=expanded > expanded.rs; rustfmt expanded.rs
@ -20,12 +20,21 @@ See [cargo expand](https://github.com/dtolnay/cargo-expand) for a more elaborate
## Running with Valgrind
Valgrind is a tool to detect memory managment bugs such as memory leaks.
Valgrind is a tool to detect memory management bugs such as memory leaks.
You first need to installa debug build of python, otherwise valgrind won't produce usable results. In ubuntu there's e.g. a `python3-dbg` package.
You first need to install a debug build of python, otherwise valgrind won't produce usable results. In ubuntu there's e.g. a `python3-dbg` package.
Activate an environment with the debug interpreter and recompile. If you're on linux, use `ldd` with the name of you're binary and check that you're linking e.g. `libpython3.6dm.so.1.0` instead of `libpython3.6m.so.1.0`.
[Download the suppressions file for cpython](https://raw.githubusercontent.com/python/cpython/master/Misc/valgrind-python.supp).
Run valgrind with `valgrind --suppressions=valgrind-python.supp ./my-command --with-options`
## Getting a stacktrace
The best start to investigate a crash such as an segmentation fault is a backtrace.
* Link against a debug build of python as described in the previous chapter
* Run `gdb <my-binary>`
* Enter `r` to run
* After the crash occurred, enter `bt` or `bt full` to print the stacktrace

View file

@ -5,6 +5,7 @@
You can use the `create_exception!` macro to define a new exception type:
```rust
# extern crate pyo3;
use pyo3::create_exception;
create_exception!(module, MyError, pyo3::exceptions::Exception);
@ -16,6 +17,7 @@ create_exception!(module, MyError, pyo3::exceptions::Exception);
For example:
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::types::PyDict;
@ -40,6 +42,7 @@ fn main() {
To raise an exception, first you need to obtain an exception type and construct a new [`PyErr`](https://docs.rs/pyo3/0.2.7/struct.PyErr.html), then call [`PyErr::restore()`](https://docs.rs/pyo3/0.2.7/struct.PyErr.html#method.restore) method to write the exception back to the Python interpreter's global state.
```rust
# extern crate pyo3;
use pyo3::{Python, PyErr};
use pyo3::exceptions;
@ -64,6 +67,7 @@ has corresponding rust type, exceptions defined by `create_exception!` and `impo
have rust type as well.
```rust
# extern crate pyo3;
# use pyo3::exceptions;
# use pyo3::prelude::*;
# fn check_for_error() -> bool {false}
@ -82,6 +86,7 @@ Python has an [`isinstance`](https://docs.python.org/3/library/functions.html#is
in `PyO3` there is a [`Python::is_instance()`](https://docs.rs/pyo3/0.2.7/struct.Python.html#method.is_instance) method which does the same thing.
```rust
# extern crate pyo3;
use pyo3::Python;
use pyo3::types::{PyBool, PyList};
@ -100,6 +105,7 @@ fn main() {
To check the type of an exception, you can simply do:
```rust
# extern crate pyo3;
# use pyo3::exceptions;
# use pyo3::prelude::*;
# fn main() {
@ -116,7 +122,7 @@ The vast majority of operations in this library will return [`PyResult<T>`](http
This is an alias for the type `Result<T, PyErr>`.
A [`PyErr`](https://docs.rs/pyo3/0.2.7/struct.PyErr.html) represents a Python exception.
Errors within the `Pyo3` library are also exposed as Python exceptions.
Errors within the PyO3 library are also exposed as Python exceptions.
PyO3 library handles python exception in two stages. During first stage `PyErr` instance get
created. At this stage python GIL is not required. During second stage, actual python
@ -151,6 +157,7 @@ The code snippet above will raise `OSError` in Python if `TcpListener::bind()` r
types so `try!` macro or `?` operator can be used.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
fn parse_int(s: String) -> PyResult<usize> {
@ -168,6 +175,7 @@ It is possible to use exception defined in python code as native rust types.
for that exception.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::import_exception;

View file

@ -6,6 +6,7 @@ the function to a [module](./module.md)
One way is defining the function in the module definition.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
#[pymodule]
@ -30,6 +31,7 @@ as first parameter, the function name as second and an instance of `Python`
as third.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
@ -60,6 +62,7 @@ built-ins are new in Python 3 — in Python 2, it is simply considered to be par
of the doc-string.
```rust
# extern crate pyo3;
use pyo3::prelude::*;
/// add(a, b, /)
@ -73,7 +76,7 @@ fn add(a: u64, b: u64) -> u64 {
```
When annotated like this, signatures are also correctly displayed in IPython.
```
```ignore
>>> pyo3_test.add?
Signature: pyo3_test.add(a, b, /)
Docstring: This function adds two unsigned 64-bit integers.

View file

@ -10,7 +10,7 @@ A comparison with rust-cpython can be found [in the guide](https://pyo3.rs/maste
## Usage
Pyo3 supports python 2.7 as well as python 3.5 and up. The minimum required rust version is 1.30.0-nightly 2018-08-18.
PyO3 supports python 2.7 as well as python 3.5 and up. The minimum required rust version is 1.30.0-nightly 2018-08-18.
You can either write a native python module in rust or use python from a rust binary.
@ -24,7 +24,7 @@ sudo apt install python3-dev python-dev
## Using rust from python
Pyo3 can be used to generate a native python module.
PyO3 can be used to generate a native python module.
**`Cargo.toml`:**
@ -45,6 +45,7 @@ features = ["extension-module"]
**`src/lib.rs`**
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
@ -89,6 +90,7 @@ pyo3 = "0.5"
Example program displaying the value of `sys.version`:
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::types::PyDict;

View file

@ -3,6 +3,7 @@
As shown in the Getting Started chapter, you can create a module as follows:
```rust
# extern crate pyo3;
use pyo3::prelude::*;
// add bindings to the generated python module
@ -11,7 +12,7 @@ use pyo3::prelude::*;
#[pymodule]
fn rust2py(py: Python, m: &PyModule) -> PyResult<()> {
// pyo3 aware function. All of our python interface could be declared in a separate module.
// 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, "sum_as_string")]
@ -52,6 +53,7 @@ Which means that the above Python code will print `This module is implemented in
In python, modules are first class objects. This means can store them as values or add them to dicts or other modules:
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::{wrap_pyfunction, wrap_pymodule};
use pyo3::types::PyDict;

View file

@ -1,7 +1,7 @@
# Parallelism
CPython has an infamous GIL(Global Interpreter Lock) prevents developers
getting true parallelism. With `pyo3` you can release GIL when executing
getting true parallelism. With PyO3 you can release GIL when executing
Rust code to achieve true parallelism.
The [`Python::allow_threads`](https://docs.rs/pyo3/0.2.7/struct.Python.html#method.allow_threads)
@ -47,7 +47,7 @@ fn word_count(py: Python, m: &PyModule) -> PyResult<()> {
## Benchmark
Let's benchmark the `word-count` example to verify that we did unlock true parallelism with `pyo3`.
Let's benchmark the `word-count` example to verify that we did unlock true parallelism with PyO3.
We are using `pytest-benchmark` to benchmark three word count functions:
1. [Pure Python version](https://github.com/PyO3/pyo3/blob/master/examples/word-count/word_count/__init__.py#L9)

View file

@ -1,12 +1,12 @@
# Appendix: pyo3 and rust-cpython
# Appendix: PyO3 and rust-cpython
Pyo3 began as fork of [rust-cpython](https://github.com/dgrunwald/rust-cpython) when rust-cpython wasn't maintained. Over the time pyo3 has become fundamentally different from rust-cpython.
PyO3 began as fork of [rust-cpython](https://github.com/dgrunwald/rust-cpython) when rust-cpython wasn't maintained. Over the time pyo3 has become fundamentally different from rust-cpython.
This chapter is based on the discussion in [PyO3/pyo3#55](https://github.com/PyO3/pyo3/issues/55).
## Macros
While rust-cpython has a macro based dsl for declaring modules and classes, pyo3 use proc macros and specialization. Pyo3 also doesn't change your struct and functions so you can still use them as normal rust functions. The disadvantage is that proc macros and specialization currently only work on nightly.
While rust-cpython has a macro based dsl for declaring modules and classes, PyO3 use proc macros and specialization. PyO3 also doesn't change your struct and functions so you can still use them as normal rust functions. The disadvantage is that proc macros and specialization currently only work on nightly.
**rust-cpython**
@ -25,6 +25,7 @@ py_class!(class MyClass |py| {
**pyo3**
```rust
# extern crate pyo3;
use pyo3::prelude::*;
use pyo3::PyRawObject;
@ -52,7 +53,7 @@ impl MyClass {
## Ownership and lifetimes
All objects are owned by pyo3 library and all apis available with references, while in rust-cpython, you own python objects.
All objects are owned by PyO3 library and all apis available with references, while in rust-cpython, you own python objects.
Here is example of PyList api:
@ -78,10 +79,10 @@ impl PyList {
}
```
Because pyo3 allows only references to python object, all reference have the Gil lifetime. So the python object is not required, and it is safe to have functions like `fn py<'p>(&'p self) -> Python<'p> {}`.
Because PyO3 allows only references to python object, all reference have the Gil lifetime. So the python object is not required, and it is safe to have functions like `fn py<'p>(&'p self) -> Python<'p> {}`.
## Error handling
rust-cpython requires a `Python` parameter for `PyErr`, so error handling ergonomics is pretty bad. It is not possible to use `?` with rust errors.
`pyo3` on other hand does not require `Python` for `PyErr`, it is only required if you want to raise an exception in python with the `PyErr::restore()` method. Due to the `std::convert::From<Err> for PyErr` trait `?` is supported automatically.
PyO3 on other hand does not require `Python` for `PyErr`, it is only required if you want to raise an exception in python with the `PyErr::restore()` method. Due to the `std::convert::From<Err> for PyErr` trait `?` is supported automatically.

View file

@ -19,76 +19,76 @@ pub const OBJECT: Proto = Proto {
name: "__getattr__",
arg: "Name",
pyres: true,
proto: "::pyo3::class::basic::PyObjectGetAttrProtocol",
proto: "pyo3::class::basic::PyObjectGetAttrProtocol",
},
MethodProto::Ternary {
name: "__setattr__",
arg1: "Name",
arg2: "Value",
pyres: true,
proto: "::pyo3::class::basic::PyObjectSetAttrProtocol",
proto: "pyo3::class::basic::PyObjectSetAttrProtocol",
},
MethodProto::Binary {
name: "__delattr__",
arg: "Name",
pyres: true,
proto: "::pyo3::class::basic::PyObjectDelAttrProtocol",
proto: "pyo3::class::basic::PyObjectDelAttrProtocol",
},
MethodProto::Unary {
name: "__str__",
pyres: true,
proto: "::pyo3::class::basic::PyObjectStrProtocol",
proto: "pyo3::class::basic::PyObjectStrProtocol",
},
MethodProto::Unary {
name: "__repr__",
pyres: true,
proto: "::pyo3::class::basic::PyObjectReprProtocol",
proto: "pyo3::class::basic::PyObjectReprProtocol",
},
MethodProto::Binary {
name: "__format__",
arg: "Format",
pyres: true,
proto: "::pyo3::class::basic::PyObjectFormatProtocol",
proto: "pyo3::class::basic::PyObjectFormatProtocol",
},
MethodProto::Unary {
name: "__hash__",
pyres: false,
proto: "::pyo3::class::basic::PyObjectHashProtocol",
proto: "pyo3::class::basic::PyObjectHashProtocol",
},
MethodProto::Unary {
name: "__bytes__",
pyres: true,
proto: "::pyo3::class::basic::PyObjectBytesProtocol",
proto: "pyo3::class::basic::PyObjectBytesProtocol",
},
MethodProto::Unary {
name: "__unicode__",
pyres: true,
proto: "::pyo3::class::basic::PyObjectUnicodeProtocol",
proto: "pyo3::class::basic::PyObjectUnicodeProtocol",
},
MethodProto::Unary {
name: "__bool__",
pyres: false,
proto: "::pyo3::class::basic::PyObjectBoolProtocol",
proto: "pyo3::class::basic::PyObjectBoolProtocol",
},
MethodProto::Binary {
name: "__richcmp__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::basic::PyObjectRichcmpProtocol",
proto: "pyo3::class::basic::PyObjectRichcmpProtocol",
},
],
py_methods: &[
PyMethod {
name: "__format__",
proto: "::pyo3::class::basic::FormatProtocolImpl",
proto: "pyo3::class::basic::FormatProtocolImpl",
},
PyMethod {
name: "__bytes__",
proto: "::pyo3::class::basic::BytesProtocolImpl",
proto: "pyo3::class::basic::BytesProtocolImpl",
},
PyMethod {
name: "__unicode__",
proto: "::pyo3::class::basic::UnicodeProtocolImpl",
proto: "pyo3::class::basic::UnicodeProtocolImpl",
},
],
};
@ -99,39 +99,39 @@ pub const ASYNC: Proto = Proto {
MethodProto::Unary {
name: "__await__",
pyres: true,
proto: "::pyo3::class::pyasync::PyAsyncAwaitProtocol",
proto: "pyo3::class::pyasync::PyAsyncAwaitProtocol",
},
MethodProto::Unary {
name: "__aiter__",
pyres: true,
proto: "::pyo3::class::pyasync::PyAsyncAiterProtocol",
proto: "pyo3::class::pyasync::PyAsyncAiterProtocol",
},
MethodProto::Unary {
name: "__anext__",
pyres: true,
proto: "::pyo3::class::pyasync::PyAsyncAnextProtocol",
proto: "pyo3::class::pyasync::PyAsyncAnextProtocol",
},
MethodProto::Unary {
name: "__aenter__",
pyres: true,
proto: "::pyo3::class::pyasync::PyAsyncAenterProtocol",
proto: "pyo3::class::pyasync::PyAsyncAenterProtocol",
},
MethodProto::Quaternary {
name: "__aexit__",
arg1: "ExcType",
arg2: "ExcValue",
arg3: "Traceback",
proto: "::pyo3::class::pyasync::PyAsyncAexitProtocol",
proto: "pyo3::class::pyasync::PyAsyncAexitProtocol",
},
],
py_methods: &[
PyMethod {
name: "__aenter__",
proto: "::pyo3::class::pyasync::PyAsyncAenterProtocolImpl",
proto: "pyo3::class::pyasync::PyAsyncAenterProtocolImpl",
},
PyMethod {
name: "__aexit__",
proto: "::pyo3::class::pyasync::PyAsyncAexitProtocolImpl",
proto: "pyo3::class::pyasync::PyAsyncAexitProtocolImpl",
},
],
};
@ -142,12 +142,12 @@ pub const BUFFER: Proto = Proto {
MethodProto::Unary {
name: "bf_getbuffer",
pyres: false,
proto: "::pyo3::class::buffer::PyBufferGetBufferProtocol",
proto: "pyo3::class::buffer::PyBufferGetBufferProtocol",
},
MethodProto::Unary {
name: "bf_releasebuffer",
pyres: false,
proto: "::pyo3::class::buffer::PyBufferReleaseBufferProtocol",
proto: "pyo3::class::buffer::PyBufferReleaseBufferProtocol",
},
],
py_methods: &[],
@ -159,24 +159,24 @@ pub const CONTEXT: Proto = Proto {
MethodProto::Unary {
name: "__enter__",
pyres: true,
proto: "::pyo3::class::context::PyContextEnterProtocol",
proto: "pyo3::class::context::PyContextEnterProtocol",
},
MethodProto::Quaternary {
name: "__exit__",
arg1: "ExcType",
arg2: "ExcValue",
arg3: "Traceback",
proto: "::pyo3::class::context::PyContextExitProtocol",
proto: "pyo3::class::context::PyContextExitProtocol",
},
],
py_methods: &[
PyMethod {
name: "__enter__",
proto: "::pyo3::class::context::PyContextEnterProtocolImpl",
proto: "pyo3::class::context::PyContextEnterProtocolImpl",
},
PyMethod {
name: "__exit__",
proto: "::pyo3::class::context::PyContextExitProtocolImpl",
proto: "pyo3::class::context::PyContextExitProtocolImpl",
},
],
};
@ -186,11 +186,11 @@ pub const GC: Proto = Proto {
methods: &[
MethodProto::Free {
name: "__traverse__",
proto: "::pyo3::class::gc::PyGCTraverseProtocol",
proto: "pyo3::class::gc::PyGCTraverseProtocol",
},
MethodProto::Free {
name: "__clear__",
proto: "::pyo3::class::gc::PyGCClearProtocol",
proto: "pyo3::class::gc::PyGCClearProtocol",
},
],
py_methods: &[],
@ -204,36 +204,36 @@ pub const DESCR: Proto = Proto {
arg1: "Inst",
arg2: "Owner",
pyres: true,
proto: "::pyo3::class::descr::PyDescrGetProtocol",
proto: "pyo3::class::descr::PyDescrGetProtocol",
},
MethodProto::Ternary {
name: "__set__",
arg1: "Inst",
arg2: "Value",
pyres: true,
proto: "::pyo3::class::descr::PyDescrSetProtocol",
proto: "pyo3::class::descr::PyDescrSetProtocol",
},
MethodProto::Binary {
name: "__det__",
arg: "Inst",
pyres: false,
proto: "::pyo3::class::descr::PyDescrDelProtocol",
proto: "pyo3::class::descr::PyDescrDelProtocol",
},
MethodProto::Binary {
name: "__set_name__",
arg: "Inst",
pyres: false,
proto: "::pyo3::class::descr::PyDescrSetNameProtocol",
proto: "pyo3::class::descr::PyDescrSetNameProtocol",
},
],
py_methods: &[
PyMethod {
name: "__del__",
proto: "::pyo3::class::context::PyDescrDelProtocolImpl",
proto: "pyo3::class::context::PyDescrDelProtocolImpl",
},
PyMethod {
name: "__set_name__",
proto: "::pyo3::class::context::PyDescrNameProtocolImpl",
proto: "pyo3::class::context::PyDescrNameProtocolImpl",
},
],
};
@ -245,12 +245,12 @@ pub const ITER: Proto = Proto {
MethodProto::Unary {
name: "__iter__",
pyres: true,
proto: "::pyo3::class::iter::PyIterIterProtocol",
proto: "pyo3::class::iter::PyIterIterProtocol",
},
MethodProto::Unary {
name: "__next__",
pyres: true,
proto: "::pyo3::class::iter::PyIterNextProtocol",
proto: "pyo3::class::iter::PyIterNextProtocol",
},
],
};
@ -261,56 +261,56 @@ pub const MAPPING: Proto = Proto {
MethodProto::Unary {
name: "__len__",
pyres: false,
proto: "::pyo3::class::mapping::PyMappingLenProtocol",
proto: "pyo3::class::mapping::PyMappingLenProtocol",
},
MethodProto::Binary {
name: "__getitem__",
arg: "Key",
pyres: true,
proto: "::pyo3::class::mapping::PyMappingGetItemProtocol",
proto: "pyo3::class::mapping::PyMappingGetItemProtocol",
},
MethodProto::Ternary {
name: "__setitem__",
arg1: "Key",
arg2: "Value",
pyres: false,
proto: "::pyo3::class::mapping::PyMappingSetItemProtocol",
proto: "pyo3::class::mapping::PyMappingSetItemProtocol",
},
MethodProto::Binary {
name: "__delitem__",
arg: "Key",
pyres: false,
proto: "::pyo3::class::mapping::PyMappingDelItemProtocol",
proto: "pyo3::class::mapping::PyMappingDelItemProtocol",
},
MethodProto::Binary {
name: "__contains__",
arg: "Value",
pyres: false,
proto: "::pyo3::class::mapping::PyMappingContainsProtocol",
proto: "pyo3::class::mapping::PyMappingContainsProtocol",
},
MethodProto::Unary {
name: "__reversed__",
pyres: true,
proto: "::pyo3::class::mapping::PyMappingReversedProtocol",
proto: "pyo3::class::mapping::PyMappingReversedProtocol",
},
MethodProto::Unary {
name: "__iter__",
pyres: true,
proto: "::pyo3::class::mapping::PyMappingIterProtocol",
proto: "pyo3::class::mapping::PyMappingIterProtocol",
},
],
py_methods: &[
PyMethod {
name: "__iter__",
proto: "::pyo3::class::mapping::PyMappingIterProtocolImpl",
proto: "pyo3::class::mapping::PyMappingIterProtocolImpl",
},
PyMethod {
name: "__contains__",
proto: "::pyo3::class::mapping::PyMappingContainsProtocolImpl",
proto: "pyo3::class::mapping::PyMappingContainsProtocolImpl",
},
PyMethod {
name: "__reversed__",
proto: "::pyo3::class::mapping::PyMappingReversedProtocolImpl",
proto: "pyo3::class::mapping::PyMappingReversedProtocolImpl",
},
],
};
@ -380,56 +380,56 @@ pub const NUM: Proto = Proto {
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberAddProtocol",
proto: "pyo3::class::number::PyNumberAddProtocol",
},
MethodProto::BinaryS {
name: "__sub__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberSubProtocol",
proto: "pyo3::class::number::PyNumberSubProtocol",
},
MethodProto::BinaryS {
name: "__mul__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberMulProtocol",
proto: "pyo3::class::number::PyNumberMulProtocol",
},
MethodProto::BinaryS {
name: "__matmul__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberMatmulProtocol",
proto: "pyo3::class::number::PyNumberMatmulProtocol",
},
MethodProto::BinaryS {
name: "__truediv__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberTruedivProtocol",
proto: "pyo3::class::number::PyNumberTruedivProtocol",
},
MethodProto::BinaryS {
name: "__floordiv__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberFloordivProtocol",
proto: "pyo3::class::number::PyNumberFloordivProtocol",
},
MethodProto::BinaryS {
name: "__mod__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberModProtocol",
proto: "pyo3::class::number::PyNumberModProtocol",
},
MethodProto::BinaryS {
name: "__divmod__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberDivmodProtocol",
proto: "pyo3::class::number::PyNumberDivmodProtocol",
},
MethodProto::TernaryS {
name: "__pow__",
@ -437,317 +437,317 @@ pub const NUM: Proto = Proto {
arg2: "Right",
arg3: "Modulo",
pyres: true,
proto: "::pyo3::class::number::PyNumberPowProtocol",
proto: "pyo3::class::number::PyNumberPowProtocol",
},
MethodProto::BinaryS {
name: "__lshift__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberLShiftProtocol",
proto: "pyo3::class::number::PyNumberLShiftProtocol",
},
MethodProto::BinaryS {
name: "__rshift__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberRShiftProtocol",
proto: "pyo3::class::number::PyNumberRShiftProtocol",
},
MethodProto::BinaryS {
name: "__and__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberAndProtocol",
proto: "pyo3::class::number::PyNumberAndProtocol",
},
MethodProto::BinaryS {
name: "__xor__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberXorProtocol",
proto: "pyo3::class::number::PyNumberXorProtocol",
},
MethodProto::BinaryS {
name: "__or__",
arg1: "Left",
arg2: "Right",
pyres: true,
proto: "::pyo3::class::number::PyNumberOrProtocol",
proto: "pyo3::class::number::PyNumberOrProtocol",
},
MethodProto::Binary {
name: "__radd__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRAddProtocol",
proto: "pyo3::class::number::PyNumberRAddProtocol",
},
MethodProto::Binary {
name: "__rsub__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRSubProtocol",
proto: "pyo3::class::number::PyNumberRSubProtocol",
},
MethodProto::Binary {
name: "__rmul__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRMulProtocol",
proto: "pyo3::class::number::PyNumberRMulProtocol",
},
MethodProto::Binary {
name: "__rmatmul__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRMatmulProtocol",
proto: "pyo3::class::number::PyNumberRMatmulProtocol",
},
MethodProto::Binary {
name: "__rtruediv__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRTruedivProtocol",
proto: "pyo3::class::number::PyNumberRTruedivProtocol",
},
MethodProto::Binary {
name: "__rfloordiv__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRFloordivProtocol",
proto: "pyo3::class::number::PyNumberRFloordivProtocol",
},
MethodProto::Binary {
name: "__rmod__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRModProtocol",
proto: "pyo3::class::number::PyNumberRModProtocol",
},
MethodProto::Binary {
name: "__rdivmod__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRDivmodProtocol",
proto: "pyo3::class::number::PyNumberRDivmodProtocol",
},
MethodProto::Ternary {
name: "__rpow__",
arg1: "Other",
arg2: "Modulo",
pyres: true,
proto: "::pyo3::class::number::PyNumberRPowProtocol",
proto: "pyo3::class::number::PyNumberRPowProtocol",
},
MethodProto::Binary {
name: "__rlshift__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRLShiftProtocol",
proto: "pyo3::class::number::PyNumberRLShiftProtocol",
},
MethodProto::Binary {
name: "__rrshift__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRRShiftProtocol",
proto: "pyo3::class::number::PyNumberRRShiftProtocol",
},
MethodProto::Binary {
name: "__rand__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRAndProtocol",
proto: "pyo3::class::number::PyNumberRAndProtocol",
},
MethodProto::Binary {
name: "__rxor__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberRXorProtocol",
proto: "pyo3::class::number::PyNumberRXorProtocol",
},
MethodProto::Binary {
name: "__ror__",
arg: "Other",
pyres: true,
proto: "::pyo3::class::number::PyNumberROrProtocol",
proto: "pyo3::class::number::PyNumberROrProtocol",
},
MethodProto::Binary {
name: "__iadd__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIAddProtocol",
proto: "pyo3::class::number::PyNumberIAddProtocol",
},
MethodProto::Binary {
name: "__isub__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberISubProtocol",
proto: "pyo3::class::number::PyNumberISubProtocol",
},
MethodProto::Binary {
name: "__imul__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIMulProtocol",
proto: "pyo3::class::number::PyNumberIMulProtocol",
},
MethodProto::Binary {
name: "__imatmul__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIMatmulProtocol",
proto: "pyo3::class::number::PyNumberIMatmulProtocol",
},
MethodProto::Binary {
name: "__itruediv__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberITruedivProtocol",
proto: "pyo3::class::number::PyNumberITruedivProtocol",
},
MethodProto::Binary {
name: "__ifloordiv__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIFloordivProtocol",
proto: "pyo3::class::number::PyNumberIFloordivProtocol",
},
MethodProto::Binary {
name: "__imod__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIModProtocol",
proto: "pyo3::class::number::PyNumberIModProtocol",
},
MethodProto::Ternary {
name: "__ipow__",
arg1: "Other",
arg2: "Modulo",
pyres: false,
proto: "::pyo3::class::number::PyNumberIPowProtocol",
proto: "pyo3::class::number::PyNumberIPowProtocol",
},
MethodProto::Binary {
name: "__ilshift__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberILShiftProtocol",
proto: "pyo3::class::number::PyNumberILShiftProtocol",
},
MethodProto::Binary {
name: "__irshift__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIRShiftProtocol",
proto: "pyo3::class::number::PyNumberIRShiftProtocol",
},
MethodProto::Binary {
name: "__iand__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIAndProtocol",
proto: "pyo3::class::number::PyNumberIAndProtocol",
},
MethodProto::Binary {
name: "__ixor__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIXorProtocol",
proto: "pyo3::class::number::PyNumberIXorProtocol",
},
MethodProto::Binary {
name: "__ior__",
arg: "Other",
pyres: false,
proto: "::pyo3::class::number::PyNumberIOrProtocol",
proto: "pyo3::class::number::PyNumberIOrProtocol",
},
MethodProto::Unary {
name: "__neg__",
pyres: true,
proto: "::pyo3::class::number::PyNumberNegProtocol",
proto: "pyo3::class::number::PyNumberNegProtocol",
},
MethodProto::Unary {
name: "__pos__",
pyres: true,
proto: "::pyo3::class::number::PyNumberPosProtocol",
proto: "pyo3::class::number::PyNumberPosProtocol",
},
MethodProto::Unary {
name: "__abs__",
pyres: true,
proto: "::pyo3::class::number::PyNumberAbsProtocol",
proto: "pyo3::class::number::PyNumberAbsProtocol",
},
MethodProto::Unary {
name: "__invert__",
pyres: true,
proto: "::pyo3::class::number::PyNumberInvertProtocol",
proto: "pyo3::class::number::PyNumberInvertProtocol",
},
MethodProto::Unary {
name: "__complex__",
pyres: true,
proto: "::pyo3::class::number::PyNumberComplexProtocol",
proto: "pyo3::class::number::PyNumberComplexProtocol",
},
MethodProto::Unary {
name: "__int__",
pyres: true,
proto: "::pyo3::class::number::PyNumberIntProtocol",
proto: "pyo3::class::number::PyNumberIntProtocol",
},
MethodProto::Unary {
name: "__float__",
pyres: true,
proto: "::pyo3::class::number::PyNumberFloatProtocol",
proto: "pyo3::class::number::PyNumberFloatProtocol",
},
MethodProto::Unary {
name: "__round__",
pyres: true,
proto: "::pyo3::class::number::PyNumberRoundProtocol",
proto: "pyo3::class::number::PyNumberRoundProtocol",
},
MethodProto::Unary {
name: "__index__",
pyres: true,
proto: "::pyo3::class::number::PyNumberIndexProtocol",
proto: "pyo3::class::number::PyNumberIndexProtocol",
},
],
py_methods: &[
PyMethod {
name: "__radd__",
proto: "::pyo3::class::number::PyNumberRAddProtocolImpl",
proto: "pyo3::class::number::PyNumberRAddProtocolImpl",
},
PyMethod {
name: "__rsub__",
proto: "::pyo3::class::number::PyNumberRSubProtocolImpl",
proto: "pyo3::class::number::PyNumberRSubProtocolImpl",
},
PyMethod {
name: "__rmul__",
proto: "::pyo3::class::number::PyNumberRMulProtocolImpl",
proto: "pyo3::class::number::PyNumberRMulProtocolImpl",
},
PyMethod {
name: "__rmatmul__",
proto: "::pyo3::class::number::PyNumberRMatmulProtocolImpl",
proto: "pyo3::class::number::PyNumberRMatmulProtocolImpl",
},
PyMethod {
name: "__rtruediv__",
proto: "::pyo3::class::number::PyNumberRTruedivProtocolImpl",
proto: "pyo3::class::number::PyNumberRTruedivProtocolImpl",
},
PyMethod {
name: "__rfloordiv__",
proto: "::pyo3::class::number::PyNumberRFloordivProtocolImpl",
proto: "pyo3::class::number::PyNumberRFloordivProtocolImpl",
},
PyMethod {
name: "__rmod__",
proto: "::pyo3::class::number::PyNumberRModProtocolImpl",
proto: "pyo3::class::number::PyNumberRModProtocolImpl",
},
PyMethod {
name: "__rdivmod__",
proto: "::pyo3::class::number::PyNumberRDivmodProtocolImpl",
proto: "pyo3::class::number::PyNumberRDivmodProtocolImpl",
},
PyMethod {
name: "__rpow__",
proto: "::pyo3::class::number::PyNumberRPowProtocolImpl",
proto: "pyo3::class::number::PyNumberRPowProtocolImpl",
},
PyMethod {
name: "__rlshift__",
proto: "::pyo3::class::number::PyNumberRLShiftProtocolImpl",
proto: "pyo3::class::number::PyNumberRLShiftProtocolImpl",
},
PyMethod {
name: "__rrshift__",
proto: "::pyo3::class::number::PyNumberRRShiftProtocolImpl",
proto: "pyo3::class::number::PyNumberRRShiftProtocolImpl",
},
PyMethod {
name: "__rand__",
proto: "::pyo3::class::number::PyNumberRAndProtocolImpl",
proto: "pyo3::class::number::PyNumberRAndProtocolImpl",
},
PyMethod {
name: "__rxor__",
proto: "::pyo3::class::number::PyNumberRXorProtocolImpl",
proto: "pyo3::class::number::PyNumberRXorProtocolImpl",
},
PyMethod {
name: "__ror__",
proto: "::pyo3::class::number::PyNumberROrProtocolImpl",
proto: "pyo3::class::number::PyNumberROrProtocolImpl",
},
PyMethod {
name: "__complex__",
proto: "::pyo3::class::number::PyNumberComplexProtocolImpl",
proto: "pyo3::class::number::PyNumberComplexProtocolImpl",
},
PyMethod {
name: "__round__",
proto: "::pyo3::class::number::PyNumberRoundProtocolImpl",
proto: "pyo3::class::number::PyNumberRoundProtocolImpl",
},
],
};

View file

@ -17,6 +17,6 @@ mod utils;
pub use module::{add_fn_to_module, process_functions_in_module, py2_init, py3_init};
pub use pyclass::{build_py_class, PyClassArgs};
pub use pyfunction::PyFunctionAttr;
pub use pyimpl::build_py_methods;
pub use pyimpl::{build_py_methods, impl_methods};
pub use pyproto::build_py_proto;
pub use utils::get_doc;

View file

@ -21,8 +21,8 @@ pub fn py3_init(fnname: &Ident, name: &Ident, doc: syn::Lit) -> TokenStream {
#[allow(non_snake_case)]
/// This autogenerated function is called by the python interpreter when importing
/// the module.
pub unsafe extern "C" fn #cb_name() -> *mut ::pyo3::ffi::PyObject {
::pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
pub unsafe extern "C" fn #cb_name() -> *mut pyo3::ffi::PyObject {
pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
}
}
}
@ -34,7 +34,7 @@ pub fn py2_init(fnname: &Ident, name: &Ident, doc: syn::Lit) -> TokenStream {
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn #cb_name() {
::pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
}
}
}
@ -190,20 +190,20 @@ pub fn add_fn_to_module(
let doc = utils::get_doc(&func.attrs, true);
let tokens = quote! {
fn #function_wrapper_ident(py: ::pyo3::Python) -> ::pyo3::PyObject {
fn #function_wrapper_ident(py: pyo3::Python) -> pyo3::PyObject {
#wrapper
let _def = ::pyo3::class::PyMethodDef {
let _def = pyo3::class::PyMethodDef {
ml_name: stringify!(#python_name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
};
let function = unsafe {
::pyo3::PyObject::from_owned_ptr_or_panic(
pyo3::PyObject::from_owned_ptr_or_panic(
py,
::pyo3::ffi::PyCFunction_New(
pyo3::ffi::PyCFunction_New(
Box::into_raw(Box::new(_def.as_method_def())),
::std::ptr::null_mut()
)
@ -228,21 +228,21 @@ fn function_c_wrapper(name: &Ident, spec: &method::FnSpec<'_>) -> TokenStream {
quote! {
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#name), "()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}

View file

@ -37,7 +37,7 @@ impl Default for PyClassArgs {
// We need the 0 as value for the constant we're later building using quote for when there
// are no other flags
flags: vec![parse_quote! {0}],
base: parse_quote! {::pyo3::types::PyAny},
base: parse_quote! {pyo3::types::PyAny},
}
}
}
@ -110,16 +110,16 @@ impl PyClassArgs {
let flag = exp.path.segments.first().unwrap().value().ident.to_string();
let path = match flag.as_str() {
"gc" => {
parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_GC}
parse_quote! {pyo3::type_object::PY_TYPE_FLAG_GC}
}
"weakref" => {
parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_WEAKREF}
parse_quote! {pyo3::type_object::PY_TYPE_FLAG_WEAKREF}
}
"subclass" => {
parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_BASETYPE}
parse_quote! {pyo3::type_object::PY_TYPE_FLAG_BASETYPE}
}
"dict" => {
parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_DICT}
parse_quote! {pyo3::type_object::PY_TYPE_FLAG_DICT}
}
_ => {
return Err(syn::Error::new_spanned(
@ -204,26 +204,26 @@ fn impl_inventory(cls: &syn::Ident) -> TokenStream {
quote! {
#[doc(hidden)]
pub struct #inventory_cls {
methods: &'static [::pyo3::class::PyMethodDefType],
methods: &'static [pyo3::class::PyMethodDefType],
}
impl ::pyo3::class::methods::PyMethodsInventory for #inventory_cls {
fn new(methods: &'static [::pyo3::class::PyMethodDefType]) -> Self {
impl pyo3::class::methods::PyMethodsInventory for #inventory_cls {
fn new(methods: &'static [pyo3::class::PyMethodDefType]) -> Self {
Self {
methods
}
}
fn get_methods(&self) -> &'static [::pyo3::class::PyMethodDefType] {
fn get_methods(&self) -> &'static [pyo3::class::PyMethodDefType] {
self.methods
}
}
impl ::pyo3::class::methods::PyMethodsInventoryDispatch for #cls {
impl pyo3::class::methods::PyMethodsInventoryDispatch for #cls {
type InventoryType = #inventory_cls;
}
::pyo3::inventory::collect!(#inventory_cls);
pyo3::inventory::collect!(#inventory_cls);
}
}
@ -241,16 +241,16 @@ fn impl_class(
let extra = {
if let Some(freelist) = &attr.freelist {
quote! {
impl ::pyo3::freelist::PyObjectWithFreeList for #cls {
impl pyo3::freelist::PyObjectWithFreeList for #cls {
#[inline]
fn get_free_list() -> &'static mut ::pyo3::freelist::FreeList<*mut ::pyo3::ffi::PyObject> {
static mut FREELIST: *mut ::pyo3::freelist::FreeList<*mut ::pyo3::ffi::PyObject> = 0 as *mut _;
fn get_free_list() -> &'static mut pyo3::freelist::FreeList<*mut pyo3::ffi::PyObject> {
static mut FREELIST: *mut pyo3::freelist::FreeList<*mut pyo3::ffi::PyObject> = 0 as *mut _;
unsafe {
if FREELIST.is_null() {
FREELIST = Box::into_raw(Box::new(
::pyo3::freelist::FreeList::with_capacity(#freelist)));
pyo3::freelist::FreeList::with_capacity(#freelist)));
<#cls as ::pyo3::type_object::PyTypeObject>::init_type();
<#cls as pyo3::type_object::PyTypeObject>::init_type();
}
&mut *FREELIST
}
@ -259,7 +259,7 @@ fn impl_class(
}
} else {
quote! {
impl ::pyo3::type_object::PyObjectAlloc for #cls {}
impl pyo3::type_object::PyObjectAlloc for #cls {}
}
}
};
@ -280,20 +280,20 @@ fn impl_class(
let mut has_dict = false;
for f in attr.flags.iter() {
if let syn::Expr::Path(ref epath) = f {
if epath.path == parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_WEAKREF} {
if epath.path == parse_quote! {pyo3::type_object::PY_TYPE_FLAG_WEAKREF} {
has_weakref = true;
} else if epath.path == parse_quote! {::pyo3::type_object::PY_TYPE_FLAG_DICT} {
} else if epath.path == parse_quote! {pyo3::type_object::PY_TYPE_FLAG_DICT} {
has_dict = true;
}
}
}
let weakref = if has_weakref {
quote! {std::mem::size_of::<*const ::pyo3::ffi::PyObject>()}
quote! {std::mem::size_of::<*const pyo3::ffi::PyObject>()}
} else {
quote! {0}
};
let dict = if has_dict {
quote! {std::mem::size_of::<*const ::pyo3::ffi::PyObject>()}
quote! {std::mem::size_of::<*const pyo3::ffi::PyObject>()}
} else {
quote! {0}
};
@ -304,7 +304,7 @@ fn impl_class(
let flags = &attr.flags;
quote! {
impl ::pyo3::type_object::PyTypeInfo for #cls {
impl pyo3::type_object::PyTypeInfo for #cls {
type Type = #cls;
type BaseType = #base;
@ -319,22 +319,22 @@ fn impl_class(
const OFFSET: isize = {
// round base_size up to next multiple of align
(
(<#base as ::pyo3::type_object::PyTypeInfo>::SIZE +
(<#base as pyo3::type_object::PyTypeInfo>::SIZE +
::std::mem::align_of::<#cls>() - 1) /
::std::mem::align_of::<#cls>() * ::std::mem::align_of::<#cls>()
) as isize
};
#[inline]
unsafe fn type_object() -> &'static mut ::pyo3::ffi::PyTypeObject {
static mut TYPE_OBJECT: ::pyo3::ffi::PyTypeObject = ::pyo3::ffi::PyTypeObject_INIT;
unsafe fn type_object() -> &'static mut pyo3::ffi::PyTypeObject {
static mut TYPE_OBJECT: pyo3::ffi::PyTypeObject = pyo3::ffi::PyTypeObject_INIT;
&mut TYPE_OBJECT
}
}
impl ::pyo3::IntoPyObject for #cls {
fn into_object(self, py: ::pyo3::Python) -> ::pyo3::PyObject {
::pyo3::Py::new(py, self).unwrap().into_object(py)
impl pyo3::IntoPyObject for #cls {
fn into_object(self, py: pyo3::Python) -> pyo3::PyObject {
pyo3::Py::new(py, self).unwrap().into_object(py)
}
}
@ -356,7 +356,7 @@ fn impl_descriptors(cls: &syn::Type, descriptors: Vec<(syn::Field, Vec<FnType>)>
FnType::Getter(_) => {
quote! {
impl #cls {
fn #name(&self) -> ::pyo3::PyResult<#field_ty> {
fn #name(&self) -> pyo3::PyResult<#field_ty> {
Ok(self.#name.clone())
}
}
@ -367,7 +367,7 @@ fn impl_descriptors(cls: &syn::Type, descriptors: Vec<(syn::Field, Vec<FnType>)>
syn::Ident::new(&format!("set_{}", name), Span::call_site());
quote! {
impl #cls {
fn #setter_name(&mut self, value: #field_ty) -> ::pyo3::PyResult<()> {
fn #setter_name(&mut self, value: #field_ty) -> pyo3::PyResult<()> {
self.#name = value;
Ok(())
}
@ -430,10 +430,10 @@ fn impl_descriptors(cls: &syn::Type, descriptors: Vec<(syn::Field, Vec<FnType>)>
quote! {
#(#methods)*
::pyo3::inventory::submit! {
pyo3::inventory::submit! {
#![crate = pyo3] {
type ClsInventory = <#cls as ::pyo3::class::methods::PyMethodsInventoryDispatch>::InventoryType;
<ClsInventory as ::pyo3::class::methods::PyMethodsInventory>::new(&[#(#py_methods),*])
type ClsInventory = <#cls as pyo3::class::methods::PyMethodsInventoryDispatch>::InventoryType;
<ClsInventory as pyo3::class::methods::PyMethodsInventory>::new(&[#(#py_methods),*])
}
}
}

View file

@ -36,10 +36,10 @@ pub fn impl_methods(ty: &syn::Type, impls: &mut Vec<syn::ImplItem>) -> TokenStre
}
quote! {
::pyo3::inventory::submit! {
pyo3::inventory::submit! {
#![crate = pyo3] {
type TyInventory = <#ty as ::pyo3::class::methods::PyMethodsInventoryDispatch>::InventoryType;
<TyInventory as ::pyo3::class::methods::PyMethodsInventory>::new(&[#(#methods),*])
type TyInventory = <#ty as pyo3::class::methods::PyMethodsInventoryDispatch>::InventoryType;
<TyInventory as pyo3::class::methods::PyMethodsInventory>::new(&[#(#methods),*])
}
}
}

View file

@ -52,21 +52,21 @@ pub fn impl_wrap(
if spec.args.is_empty() && noargs {
quote! {
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject
) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject
) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(
stringify!(#cls), ".", stringify!(#name), "()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
let _result = {
::pyo3::derive_utils::IntoPyResult::into_py_result(#body)
pyo3::derive_utils::IntoPyResult::into_py_result(#body)
};
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
} else {
@ -74,22 +74,22 @@ pub fn impl_wrap(
quote! {
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(
stringify!(#cls), ".", stringify!(#name), "()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}
@ -103,21 +103,21 @@ pub fn impl_proto_wrap(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) ->
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}
@ -132,24 +132,24 @@ pub fn impl_wrap_new(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) -> T
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_cls: *mut ::pyo3::ffi::PyTypeObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_cls: *mut pyo3::ffi::PyTypeObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
use ::pyo3::type_object::PyTypeInfo;
use pyo3::type_object::PyTypeInfo;
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
match ::pyo3::type_object::PyRawObject::new(_py, #cls::type_object(), _cls) {
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
match pyo3::type_object::PyRawObject::new(_py, #cls::type_object(), _cls) {
Ok(_obj) => {
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
match _result {
Ok(_) => ::pyo3::IntoPyPointer::into_ptr(_obj),
Ok(_) => pyo3::IntoPyPointer::into_ptr(_obj),
Err(e) => {
e.restore(_py);
::std::ptr::null_mut()
@ -180,16 +180,16 @@ fn impl_wrap_init(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) -> Toke
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> libc::c_int
_slf: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> libc::c_int
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
@ -214,21 +214,21 @@ pub fn impl_wrap_class(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) ->
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_cls: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_cls: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _cls = ::pyo3::types::PyType::from_type_ptr(_py, _cls as *mut ::pyo3::ffi::PyTypeObject);
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _cls = pyo3::types::PyType::from_type_ptr(_py, _cls as *mut pyo3::ffi::PyTypeObject);
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}
@ -243,20 +243,20 @@ pub fn impl_wrap_static(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) -
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject,
_args: *mut pyo3::ffi::PyObject,
_kwargs: *mut pyo3::ffi::PyObject) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _args = _py.from_borrowed_ptr::<pyo3::types::PyTuple>(_args);
let _kwargs: Option<&pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
pyo3::callback::cb_convert(
pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}
@ -265,17 +265,17 @@ pub fn impl_wrap_static(cls: &syn::Type, name: &syn::Ident, spec: &FnSpec<'_>) -
pub(crate) fn impl_wrap_getter(cls: &syn::Type, name: &syn::Ident) -> TokenStream {
quote! {
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject, _: *mut ::std::os::raw::c_void) -> *mut ::pyo3::ffi::PyObject
_slf: *mut pyo3::ffi::PyObject, _: *mut ::std::os::raw::c_void) -> *mut pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
match _slf.#name() {
Ok(val) => {
::pyo3::IntoPyPointer::into_ptr(val.into_object(_py))
pyo3::IntoPyPointer::into_ptr(val.into_object(_py))
}
Err(e) => {
e.restore(_py);
@ -304,16 +304,16 @@ pub(crate) fn impl_wrap_setter(
quote! {
#[allow(unused_mut)]
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_value: *mut ::pyo3::ffi::PyObject, _: *mut ::std::os::raw::c_void) -> libc::c_int
_slf: *mut pyo3::ffi::PyObject,
_value: *mut pyo3::ffi::PyObject, _: *mut ::std::os::raw::c_void) -> libc::c_int
{
const _LOCATION: &'static str = concat!(stringify!(#cls),".",stringify!(#name),"()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _pool = pyo3::GILPool::new();
let _py = pyo3::Python::assume_gil_acquired();
let _slf = _py.mut_from_borrowed_ptr::<#cls>(_slf);
let _value = _py.from_borrowed_ptr(_value);
let _result = match <#val_ty as ::pyo3::FromPyObject>::extract(_value) {
let _result = match <#val_ty as pyo3::FromPyObject>::extract(_value) {
Ok(_val) => _slf.#name(_val),
Err(e) => Err(e)
};
@ -355,7 +355,7 @@ pub fn impl_arg_params(spec: &FnSpec<'_>, body: TokenStream) -> TokenStream {
if spec.args.is_empty() {
return quote! {
let _result = {
::pyo3::derive_utils::IntoPyResult::into_py_result(#body)
pyo3::derive_utils::IntoPyResult::into_py_result(#body)
};
};
}
@ -371,7 +371,7 @@ pub fn impl_arg_params(spec: &FnSpec<'_>, body: TokenStream) -> TokenStream {
let opt = bool_to_ident(arg.optional.is_some() || spec.default_value(&arg.name).is_some());
params.push(quote! {
::pyo3::derive_utils::ParamDescription {
pyo3::derive_utils::ParamDescription {
name: stringify!(#name),
is_optional: #opt,
kw_only: #kwonly
@ -394,8 +394,8 @@ pub fn impl_arg_params(spec: &FnSpec<'_>, body: TokenStream) -> TokenStream {
// create array of arguments, and then parse
quote! {
use ::pyo3::ObjectProtocol;
const PARAMS: &'static [::pyo3::derive_utils::ParamDescription] = &[
use pyo3::ObjectProtocol;
const PARAMS: &'static [pyo3::derive_utils::ParamDescription] = &[
#(#params),*
];
@ -403,7 +403,7 @@ pub fn impl_arg_params(spec: &FnSpec<'_>, body: TokenStream) -> TokenStream {
// Workaround to use the question mark operator without rewriting everything
let _result = (|| {
::pyo3::derive_utils::parse_fn_args(
pyo3::derive_utils::parse_fn_args(
Some(_LOCATION),
PARAMS,
&_args,
@ -415,7 +415,7 @@ pub fn impl_arg_params(spec: &FnSpec<'_>, body: TokenStream) -> TokenStream {
#(#param_conversion)*
::pyo3::derive_utils::IntoPyResult::into_py_result(#body)
pyo3::derive_utils::IntoPyResult::into_py_result(#body)
})();
}
}
@ -443,7 +443,7 @@ fn impl_arg_param(
if spec.is_args(&name) {
quote! {
let #arg_name = <#ty as ::pyo3::FromPyObject>::extract(_args.as_ref())?;
let #arg_name = <#ty as pyo3::FromPyObject>::extract(_args.as_ref())?;
}
} else if spec.is_kwargs(&name) {
quote! {
@ -496,26 +496,26 @@ pub fn impl_py_method_def(
) -> TokenStream {
if spec.args.is_empty() {
quote! {
::pyo3::class::PyMethodDefType::Method({
pyo3::class::PyMethodDefType::Method({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyNoArgsFunction(__wrap),
ml_flags: ::pyo3::ffi::METH_NOARGS,
ml_meth: pyo3::class::PyMethodType::PyNoArgsFunction(__wrap),
ml_flags: pyo3::ffi::METH_NOARGS,
ml_doc: #doc,
}
})
}
} else {
quote! {
::pyo3::class::PyMethodDefType::Method({
pyo3::class::PyMethodDefType::Method({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
}
})
@ -529,13 +529,13 @@ pub fn impl_py_method_def_new(
wrapper: &TokenStream,
) -> TokenStream {
quote! {
::pyo3::class::PyMethodDefType::New({
pyo3::class::PyMethodDefType::New({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyNewFunc(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyNewFunc(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
}
})
@ -548,13 +548,13 @@ pub fn impl_py_method_def_init(
wrapper: &TokenStream,
) -> TokenStream {
quote! {
::pyo3::class::PyMethodDefType::Init({
pyo3::class::PyMethodDefType::Init({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyInitFunc(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyInitFunc(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
}
})
@ -567,14 +567,14 @@ pub fn impl_py_method_def_class(
wrapper: &TokenStream,
) -> TokenStream {
quote! {
::pyo3::class::PyMethodDefType::Class({
pyo3::class::PyMethodDefType::Class({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS |
::pyo3::ffi::METH_CLASS,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS |
pyo3::ffi::METH_CLASS,
ml_doc: #doc,
}
})
@ -587,13 +587,13 @@ pub fn impl_py_method_def_static(
wrapper: &TokenStream,
) -> TokenStream {
quote! {
::pyo3::class::PyMethodDefType::Static({
pyo3::class::PyMethodDefType::Static({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS | ::pyo3::ffi::METH_STATIC,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS | pyo3::ffi::METH_STATIC,
ml_doc: #doc,
}
})
@ -606,13 +606,13 @@ pub fn impl_py_method_def_call(
wrapper: &TokenStream,
) -> TokenStream {
quote! {
::pyo3::class::PyMethodDefType::Call({
pyo3::class::PyMethodDefType::Call({
#wrapper
::pyo3::class::PyMethodDef {
pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
}
})
@ -637,10 +637,10 @@ pub(crate) fn impl_py_setter_def(
};
quote! {
::pyo3::class::PyMethodDefType::Setter({
pyo3::class::PyMethodDefType::Setter({
#wrapper
::pyo3::class::PySetterDef {
pyo3::class::PySetterDef {
name: #n,
meth: __wrap,
doc: #doc,
@ -667,10 +667,10 @@ pub(crate) fn impl_py_getter_def(
};
quote! {
::pyo3::class::PyMethodDefType::Getter({
pyo3::class::PyMethodDefType::Getter({
#wrapper
::pyo3::class::PyGetterDef {
pyo3::class::PyGetterDef {
name: #n,
meth: __wrap,
doc: #doc,

View file

@ -84,13 +84,13 @@ fn impl_proto_impl(
impl #proto for #ty
{
#[inline]
fn #name() -> Option<::pyo3::class::methods::PyMethodDef> {
fn #name() -> Option<pyo3::class::methods::PyMethodDef> {
#meth
Some(::pyo3::class::PyMethodDef {
Some(pyo3::class::PyMethodDef {
ml_name: stringify!(#name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS,
ml_doc: ""
})
}

View file

@ -27,6 +27,8 @@ pub const PyGetSetDef_INIT: PyGetSetDef = PyGetSetDef {
closure: ptr::null_mut(),
};
pub const PyGetSetDef_DICT: PyGetSetDef = PyGetSetDef_INIT;
impl Clone for PyGetSetDef {
#[inline]
fn clone(&self) -> PyGetSetDef {

View file

@ -1,5 +1,7 @@
use crate::ffi3::methodobject::PyMethodDef;
use crate::ffi3::object::{PyObject, PyTypeObject};
use crate::ffi3::object::{
PyObject, PyObject_GenericGetDict, PyObject_GenericSetDict, PyTypeObject,
};
use crate::ffi3::structmember::PyMemberDef;
use std::os::raw::{c_char, c_int, c_void};
use std::ptr;
@ -27,6 +29,14 @@ pub const PyGetSetDef_INIT: PyGetSetDef = PyGetSetDef {
closure: ptr::null_mut(),
};
pub const PyGetSetDef_DICT: PyGetSetDef = PyGetSetDef {
name: "__dict__\0".as_ptr() as *mut c_char,
get: Some(PyObject_GenericGetDict),
set: Some(PyObject_GenericSetDict),
doc: ptr::null_mut(),
closure: ptr::null_mut(),
};
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PyClassMethodDescr_Type: PyTypeObject;

View file

@ -702,6 +702,7 @@ extern "C" {
arg2: *mut PyObject,
arg3: *mut PyObject,
) -> c_int;
pub fn PyObject_GenericGetDict(arg1: *mut PyObject, arg2: *mut c_void) -> *mut PyObject;
pub fn PyObject_GenericSetDict(
arg1: *mut PyObject,
arg2: *mut PyObject,

View file

@ -347,26 +347,28 @@ mod test {
#[test]
fn test_owned() {
gil::init_once();
let gil = Python::acquire_gil();
let py = gil.python();
let obj = get_object();
let obj_ptr = obj.as_ptr();
// Ensure that obj does not get freed
let _ref = obj.clone_ref(py);
unsafe {
let p: &'static mut ReleasePool = &mut *POOL;
let cnt;
let empty;
{
let gil = Python::acquire_gil();
let py = gil.python();
let _ = gil::register_owned(py, obj.into_nonnull());
empty = ffi::PyTuple_New(0);
cnt = ffi::Py_REFCNT(empty) - 1;
let _ = gil::register_owned(py, NonNull::new(empty).unwrap());
assert_eq!(ffi::Py_REFCNT(obj_ptr), 2);
assert_eq!(p.owned.len(), 1);
}
{
let _gil = Python::acquire_gil();
assert_eq!(p.owned.len(), 0);
assert_eq!(cnt, ffi::Py_REFCNT(empty));
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
}
}
@ -376,35 +378,33 @@ mod test {
gil::init_once();
let gil = Python::acquire_gil();
let py = gil.python();
let obj = get_object();
// Ensure that obj does not get freed
let _ref = obj.clone_ref(py);
let obj_ptr = obj.as_ptr();
unsafe {
let p: &'static mut ReleasePool = &mut *POOL;
let cnt;
let empty;
{
let _pool = GILPool::new();
assert_eq!(p.owned.len(), 0);
// empty tuple is singleton
empty = ffi::PyTuple_New(0);
cnt = ffi::Py_REFCNT(empty) - 1;
let _ = gil::register_owned(py, NonNull::new(empty).unwrap());
let _ = gil::register_owned(py, obj.into_nonnull());
assert_eq!(p.owned.len(), 1);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 2);
{
let _pool = GILPool::new();
let empty = ffi::PyTuple_New(0);
let _ = gil::register_owned(py, NonNull::new(empty).unwrap());
let obj = get_object();
let _ = gil::register_owned(py, obj.into_nonnull());
assert_eq!(p.owned.len(), 2);
}
assert_eq!(p.owned.len(), 1);
}
{
assert_eq!(p.owned.len(), 0);
assert_eq!(cnt, ffi::Py_REFCNT(empty));
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
}
}
@ -418,22 +418,20 @@ mod test {
let obj = get_object();
let obj_ptr = obj.as_ptr();
let cnt;
{
let gil = Python::acquire_gil();
let py = gil.python();
assert_eq!(p.borrowed.len(), 0);
cnt = ffi::Py_REFCNT(obj_ptr);
gil::register_borrowed(py, NonNull::new(obj_ptr).unwrap());
assert_eq!(p.borrowed.len(), 1);
assert_eq!(ffi::Py_REFCNT(obj_ptr), cnt);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
{
let _gil = Python::acquire_gil();
assert_eq!(p.borrowed.len(), 0);
assert_eq!(ffi::Py_REFCNT(obj_ptr), cnt);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
}
}
@ -447,17 +445,15 @@ mod test {
let obj = get_object();
let obj_ptr = obj.as_ptr();
let cnt;
{
let gil = Python::acquire_gil();
let py = gil.python();
assert_eq!(p.borrowed.len(), 0);
cnt = ffi::Py_REFCNT(obj_ptr);
gil::register_borrowed(py, NonNull::new(obj_ptr).unwrap());
assert_eq!(p.borrowed.len(), 1);
assert_eq!(ffi::Py_REFCNT(obj_ptr), cnt);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
{
let _pool = GILPool::new();
@ -467,43 +463,41 @@ mod test {
}
assert_eq!(p.borrowed.len(), 1);
assert_eq!(ffi::Py_REFCNT(obj_ptr), cnt);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
{
let _gil = Python::acquire_gil();
assert_eq!(p.borrowed.len(), 0);
assert_eq!(ffi::Py_REFCNT(obj_ptr), cnt);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
}
}
#[ignore]
#[test]
fn test_pyobject_drop() {
gil::init_once();
let gil = Python::acquire_gil();
let py = gil.python();
let obj = get_object();
// Ensure that obj does not get freed
let _ref = obj.clone_ref(py);
let obj_ptr = obj.as_ptr();
unsafe {
let p: &'static mut ReleasePool = &mut *POOL;
let ob;
let cnt;
let empty;
{
let gil = Python::acquire_gil();
let py = gil.python();
assert_eq!(p.owned.len(), 0);
// empty tuple is singleton
empty = ffi::PyTuple_New(0);
cnt = ffi::Py_REFCNT(empty);
ob = PyObject::from_owned_ptr(py, empty);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 2);
}
drop(ob);
assert_eq!(cnt, ffi::Py_REFCNT(empty));
drop(obj);
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
{
let _gil = Python::acquire_gil();
}
assert_eq!(cnt - 1, ffi::Py_REFCNT(empty));
assert_eq!(ffi::Py_REFCNT(obj_ptr), 1);
}
}
}

View file

@ -321,7 +321,8 @@ where
}
// __dict__ support
if T::FLAGS & PY_TYPE_FLAG_DICT != 0 {
let has_dict = T::FLAGS & PY_TYPE_FLAG_DICT != 0;
if has_dict {
offset -= std::mem::size_of::<*const ffi::PyObject>();
type_object.tp_dictoffset = offset as isize;
}
@ -392,6 +393,10 @@ where
// properties
let mut props = py_class_properties::<T>();
if cfg!(Py_3) && has_dict {
props.push(ffi::PyGetSetDef_DICT);
}
if !props.is_empty() {
props.push(ffi::PyGetSetDef_INIT);
type_object.tp_getset = Box::into_raw(props.into_boxed_slice()) as *mut _;

View file

@ -191,7 +191,7 @@ where
impl<T> IntoPyObject for Vec<T>
where
T: IntoPyObject + ToPyObject,
T: IntoPyObject,
{
fn into_object(self, py: Python) -> PyObject {
unsafe {

View file

@ -1,7 +1,11 @@
use docmatic;
use std::default::Default;
use std::path::{Path, PathBuf};
#[cfg(feature = "test-doc")]
use {
docmatic,
std::default::Default,
std::path::{Path, PathBuf},
};
#[cfg(feature = "test-doc")]
fn assert_file<P: AsRef<Path>>(path: P) {
let mut doc = docmatic::Assert::default();
if cfg!(windows) {
@ -14,8 +18,8 @@ fn assert_file<P: AsRef<Path>>(path: P) {
doc.test_file(path.as_ref())
}
#[ignore]
#[test]
#[cfg(feature = "test-doc")]
fn test_guide() {
let guide_path = PathBuf::from("guide").join("src");
for entry in guide_path.read_dir().unwrap() {
@ -23,8 +27,8 @@ fn test_guide() {
}
}
#[ignore]
#[test]
#[cfg(feature = "test-doc")]
fn test_readme() {
assert_file("README.md")
}

View file

@ -453,6 +453,22 @@ fn dunder_dict_support() {
);
}
#[cfg(Py_3)]
#[test]
fn access_dunder_dict() {
let gil = Python::acquire_gil();
let py = gil.python();
let inst = PyRef::new(py, DunderDictSupport {}).unwrap();
py_run!(
py,
inst,
r#"
inst.a = 1
assert inst.__dict__ == {'a': 1}
"#
);
}
#[pyclass(weakref, dict)]
struct WeakRefDunderDictSupport {}