Skip to content

Commit 7bdc504

Browse files
authored
Merge pull request #2567 from davidhewitt/pyclass-sequence
pyclass: add `sequence` option to implement `sq_length`
2 parents d2b4c3a + fd8026c commit 7bdc504

11 files changed

+93
-23
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2929
- Add support for generating PyPy Windows import library. [#2506](https://github.com/PyO3/pyo3/pull/2506)
3030
- Add FFI definitions for `Py_EnterRecursiveCall` and `Py_LeaveRecursiveCall`. [#2511](https://github.com/PyO3/pyo3/pull/2511)
3131
- Add `get_item_with_error` on `PyDict` that exposes `PyDict_GetItemWIthError` for non-PyPy. [#2536](https://github.com/PyO3/pyo3/pull/2536)
32+
- Add `#[pyclass(sequence)]` option. [#2567](https://github.com/PyO3/pyo3/pull/2567)
3233

3334
### Changed
3435

guide/pyclass_parameters.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
| `mapping` | Inform PyO3 that this class is a [`Mapping`][params-mapping], and so leave its implementation of sequence C-API slots empty. |
1111
| <span style="white-space: pre">`module = "module_name"`</span> | Python code will see the class as being defined in this module. Defaults to `builtins`. |
1212
| <span style="white-space: pre">`name = "python_name"`</span> | Sets the name that Python sees this class as. Defaults to the name of the Rust struct. |
13-
| <span style="white-space: pre">`text_signature = "(arg1, arg2, ...)"`</span> | Sets the text signature for the Python class' `__new__` method. |
13+
| `sequence` | Inform PyO3 that this class is a [`Sequence`][params-sequence], and so leave its C-API mapping length slot empty. |
1414
| `subclass` | Allows other Python classes and `#[pyclass]` to inherit from this class. Enums cannot be subclassed. |
15+
| <span style="white-space: pre">`text_signature = "(arg1, arg2, ...)"`</span> | Sets the text signature for the Python class' `__new__` method. |
1516
| `unsendable` | Required if your struct is not [`Send`][params-3]. Rather than using `unsendable`, consider implementing your struct in a threadsafe way by e.g. substituting [`Rc`][params-4] with [`Arc`][params-5]. By using `unsendable`, your class will panic when accessed by another thread.|
1617
| `weakref` | Allows this class to be [weakly referenceable][params-6]. |
1718

@@ -35,4 +36,5 @@ struct MyClass { }
3536
[params-4]: https://doc.rust-lang.org/std/rc/struct.Rc.html
3637
[params-5]: https://doc.rust-lang.org/std/sync/struct.Arc.html
3738
[params-6]: https://docs.python.org/3/library/weakref.html
38-
[params-mapping]: https://pyo3.rs/latest/class/protocols.html#mapping--sequence-types
39+
[params-mapping]: https://pyo3.rs/latest/class/protocols.html#mapping--sequence-types
40+
[params-sequence]: https://pyo3.rs/latest/class/protocols.html#mapping--sequence-types

guide/src/class/protocols.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,11 @@ Mapping types usually will not want the sequence slots filled. Having them fille
207207

208208
Use the `#[pyclass(mapping)]` annotation to instruct PyO3 to only fill the mapping slots, leaving the sequence ones empty. This will apply to `__getitem__`, `__setitem__`, and `__delitem__`.
209209

210+
Use the `#[pyclass(sequence)]` annotation to instruct PyO3 to fill the `sq_length` slot instead of the `mp_length` slot for `__len__`. This will help libraries such as `numpy` recognise the class as a sequence, however will also cause CPython to automatically add the sequence length to any negative indices before passing them to `__getitem__`. (`__getitem__`, `__setitem__` and `__delitem__` mapping slots are still used for sequences, for slice operations.)
211+
210212
- `__len__(<self>) -> usize`
211213

212-
Implements the built-in function `len()` for the sequence.
214+
Implements the built-in function `len()`.
213215

214216
- `__contains__(<self>, object) -> bool`
215217

guide/src/migration.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,9 @@ class ExampleContainer:
230230

231231
This class implements a Python [sequence](https://docs.python.org/3/glossary.html#term-sequence).
232232

233-
The `__len__` and `__getitem__` methods are also used to implement a Python [mapping](https://docs.python.org/3/glossary.html#term-mapping). In the Python C-API, these methods are not shared: the sequence `__len__` and `__getitem__` are defined by the `sq_len` and `sq_item` slots, and the mapping equivalents are `mp_len` and `mp_subscript`. There are similar distinctions for `__setitem__` and `__delitem__`.
233+
The `__len__` and `__getitem__` methods are also used to implement a Python [mapping](https://docs.python.org/3/glossary.html#term-mapping). In the Python C-API, these methods are not shared: the sequence `__len__` and `__getitem__` are defined by the `sq_length` and `sq_item` slots, and the mapping equivalents are `mp_length` and `mp_subscript`. There are similar distinctions for `__setitem__` and `__delitem__`.
234234

235-
Because there is no such distinction from Python, implementing these methods will fill the mapping and sequence slots simultaneously. A Python class with `__len__` implemented, for example, will have both the `sq_len` and `mp_len` slots filled.
235+
Because there is no such distinction from Python, implementing these methods will fill the mapping and sequence slots simultaneously. A Python class with `__len__` implemented, for example, will have both the `sq_length` and `mp_length` slots filled.
236236

237237
The PyO3 behavior in 0.16 has been changed to be closer to this Python behavior by default.
238238

pyo3-macros-backend/src/attributes.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub mod kw {
2323
syn::custom_keyword!(module);
2424
syn::custom_keyword!(name);
2525
syn::custom_keyword!(pass_module);
26+
syn::custom_keyword!(sequence);
2627
syn::custom_keyword!(set);
2728
syn::custom_keyword!(signature);
2829
syn::custom_keyword!(subclass);

pyo3-macros-backend/src/pyclass.rs

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ pub struct PyClassPyO3Options {
6565
pub mapping: Option<kw::mapping>,
6666
pub module: Option<ModuleAttribute>,
6767
pub name: Option<NameAttribute>,
68+
pub sequence: Option<kw::sequence>,
6869
pub subclass: Option<kw::subclass>,
6970
pub text_signature: Option<TextSignatureAttribute>,
7071
pub unsendable: Option<kw::unsendable>,
@@ -82,6 +83,7 @@ enum PyClassPyO3Option {
8283
Mapping(kw::mapping),
8384
Module(ModuleAttribute),
8485
Name(NameAttribute),
86+
Sequence(kw::sequence),
8587
Subclass(kw::subclass),
8688
TextSignature(TextSignatureAttribute),
8789
Unsendable(kw::unsendable),
@@ -109,6 +111,8 @@ impl Parse for PyClassPyO3Option {
109111
input.parse().map(PyClassPyO3Option::Module)
110112
} else if lookahead.peek(kw::name) {
111113
input.parse().map(PyClassPyO3Option::Name)
114+
} else if lookahead.peek(attributes::kw::sequence) {
115+
input.parse().map(PyClassPyO3Option::Sequence)
112116
} else if lookahead.peek(attributes::kw::subclass) {
113117
input.parse().map(PyClassPyO3Option::Subclass)
114118
} else if lookahead.peek(attributes::kw::text_signature) {
@@ -164,6 +168,7 @@ impl PyClassPyO3Options {
164168
PyClassPyO3Option::Mapping(mapping) => set_option!(mapping),
165169
PyClassPyO3Option::Module(module) => set_option!(module),
166170
PyClassPyO3Option::Name(name) => set_option!(name),
171+
PyClassPyO3Option::Sequence(sequence) => set_option!(sequence),
167172
PyClassPyO3Option::Subclass(subclass) => set_option!(subclass),
168173
PyClassPyO3Option::TextSignature(text_signature) => set_option!(text_signature),
169174
PyClassPyO3Option::Unsendable(unsendable) => set_option!(unsendable),
@@ -315,7 +320,7 @@ fn impl_class(
315320
vec![],
316321
)
317322
.doc(doc)
318-
.impl_all();
323+
.impl_all()?;
319324

320325
Ok(quote! {
321326
const _: () = {
@@ -414,7 +419,7 @@ pub fn build_py_enum(
414419
.map(|attr| (get_class_python_name(&enum_.ident, &args), attr)),
415420
);
416421
let enum_ = PyClassEnum::new(enum_)?;
417-
Ok(impl_enum(enum_, &args, doc, method_type))
422+
impl_enum(enum_, &args, doc, method_type)
418423
}
419424

420425
/// `#[pyo3()]` options for pyclass enum variants
@@ -462,7 +467,7 @@ fn impl_enum(
462467
args: &PyClassArgs,
463468
doc: PythonDoc,
464469
methods_type: PyClassMethodsType,
465-
) -> TokenStream {
470+
) -> Result<TokenStream> {
466471
let krate = get_pyo3_crate(&args.options.krate);
467472
impl_enum_class(enum_, args, doc, methods_type, krate)
468473
}
@@ -473,7 +478,7 @@ fn impl_enum_class(
473478
doc: PythonDoc,
474479
methods_type: PyClassMethodsType,
475480
krate: syn::Path,
476-
) -> TokenStream {
481+
) -> Result<TokenStream> {
477482
let cls = enum_.ident;
478483
let ty: syn::Type = syn::parse_quote!(#cls);
479484
let variants = enum_.variants;
@@ -569,9 +574,9 @@ fn impl_enum_class(
569574
default_slots,
570575
)
571576
.doc(doc)
572-
.impl_all();
577+
.impl_all()?;
573578

574-
quote! {
579+
Ok(quote! {
575580
const _: () = {
576581
use #krate as _pyo3;
577582

@@ -587,7 +592,7 @@ fn impl_enum_class(
587592
#default_richcmp
588593
}
589594
};
590-
}
595+
})
591596
}
592597

593598
fn generate_default_protocol_slot(
@@ -752,16 +757,17 @@ impl<'a> PyClassImplsBuilder<'a> {
752757
}
753758
}
754759

755-
fn impl_all(&self) -> TokenStream {
756-
vec![
760+
fn impl_all(&self) -> Result<TokenStream> {
761+
let tokens = vec![
757762
self.impl_pyclass(),
758763
self.impl_extractext(),
759764
self.impl_into_py(),
760-
self.impl_pyclassimpl(),
765+
self.impl_pyclassimpl()?,
761766
self.impl_freelist(),
762767
]
763768
.into_iter()
764-
.collect()
769+
.collect();
770+
Ok(tokens)
765771
}
766772

767773
fn impl_pyclass(&self) -> TokenStream {
@@ -828,7 +834,7 @@ impl<'a> PyClassImplsBuilder<'a> {
828834
quote! {}
829835
}
830836
}
831-
fn impl_pyclassimpl(&self) -> TokenStream {
837+
fn impl_pyclassimpl(&self) -> Result<TokenStream> {
832838
let cls = self.cls;
833839
let doc = self.doc.as_ref().map_or(quote! {"\0"}, |doc| quote! {#doc});
834840
let is_basetype = self.attr.options.subclass.is_some();
@@ -841,6 +847,12 @@ impl<'a> PyClassImplsBuilder<'a> {
841847
.unwrap_or_else(|| parse_quote! { _pyo3::PyAny });
842848
let is_subclass = self.attr.options.extends.is_some();
843849
let is_mapping: bool = self.attr.options.mapping.is_some();
850+
let is_sequence: bool = self.attr.options.sequence.is_some();
851+
852+
ensure_spanned!(
853+
!(is_mapping && is_sequence),
854+
self.cls.span() => "a `#[pyclass]` cannot be both a `mapping` and a `sequence`"
855+
);
844856

845857
let dict_offset = if self.attr.options.dict.is_some() {
846858
quote! {
@@ -959,12 +971,13 @@ impl<'a> PyClassImplsBuilder<'a> {
959971
quote! { _pyo3::PyAny }
960972
};
961973

962-
quote! {
974+
Ok(quote! {
963975
impl _pyo3::impl_::pyclass::PyClassImpl for #cls {
964976
const DOC: &'static str = #doc;
965977
const IS_BASETYPE: bool = #is_basetype;
966978
const IS_SUBCLASS: bool = #is_subclass;
967979
const IS_MAPPING: bool = #is_mapping;
980+
const IS_SEQUENCE: bool = #is_sequence;
968981

969982
type Layout = _pyo3::PyCell<Self>;
970983
type BaseType = #base;
@@ -1002,7 +1015,7 @@ impl<'a> PyClassImplsBuilder<'a> {
10021015
}
10031016

10041017
#inventory_class
1005-
}
1018+
})
10061019
}
10071020

10081021
fn impl_freelist(&self) -> TokenStream {

src/impl_/pyclass.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,9 @@ pub trait PyClassImpl: Sized {
146146
/// #[pyclass(mapping)]
147147
const IS_MAPPING: bool = false;
148148

149+
/// #[pyclass(sequence)]
150+
const IS_SEQUENCE: bool = false;
151+
149152
/// Layout
150153
type Layout: PyLayout<Self>;
151154

src/pyclass.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ where
4343
.slot(ffi::Py_tp_dealloc, tp_dealloc::<T> as *mut c_void)
4444
.set_is_basetype(T::IS_BASETYPE)
4545
.set_is_mapping(T::IS_MAPPING)
46+
.set_is_sequence(T::IS_SEQUENCE)
4647
.class_items(T::items_iter())
4748
.build(py, T::NAME, T::MODULE, std::mem::size_of::<T::Layout>())
4849
} {
@@ -63,6 +64,7 @@ struct PyTypeBuilder {
6364
/// except for that it does and we have tests.
6465
cleanup: Vec<PyTypeBuilderCleanup>,
6566
is_mapping: bool,
67+
is_sequence: bool,
6668
has_new: bool,
6769
has_dealloc: bool,
6870
has_getitem: bool,
@@ -225,6 +227,11 @@ impl PyTypeBuilder {
225227
self
226228
}
227229

230+
fn set_is_sequence(mut self, is_sequence: bool) -> Self {
231+
self.is_sequence = is_sequence;
232+
self
233+
}
234+
228235
/// # Safety
229236
/// All slots in the PyClassItemsIter should be correct
230237
unsafe fn class_items(mut self, iter: PyClassItemsIter) -> Self {
@@ -348,6 +355,15 @@ impl PyTypeBuilder {
348355
)));
349356
}
350357

358+
// For sequences, implement sq_length instead of mp_length
359+
if self.is_sequence {
360+
for slot in &mut self.slots {
361+
if slot.slot == ffi::Py_mp_length {
362+
slot.slot = ffi::Py_sq_length;
363+
}
364+
}
365+
}
366+
351367
// Add empty sentinel at the end
352368
// Safety: python expects this empty slot
353369
unsafe { self.push_slot(0, ptr::null_mut::<c_void>()) }

tests/test_sequence.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#![cfg(feature = "macros")]
22

33
use pyo3::exceptions::{PyIndexError, PyValueError};
4-
use pyo3::prelude::*;
54
use pyo3::types::{IntoPyDict, PyList, PyMapping, PySequence};
5+
use pyo3::{ffi, prelude::*, AsPyPointer};
66

77
use pyo3::py_run;
88

@@ -279,14 +279,18 @@ fn test_generic_list_set() {
279279
});
280280
}
281281

282-
#[pyclass]
282+
#[pyclass(sequence)]
283283
struct OptionList {
284284
#[pyo3(get, set)]
285285
items: Vec<Option<i64>>,
286286
}
287287

288288
#[pymethods]
289289
impl OptionList {
290+
fn __len__(&self) -> usize {
291+
self.items.len()
292+
}
293+
290294
fn __getitem__(&self, idx: isize) -> PyResult<Option<i64>> {
291295
match self.items.get(idx as usize) {
292296
Some(x) => Ok(*x),
@@ -332,3 +336,22 @@ fn sequence_is_not_mapping() {
332336
assert!(list.as_ref().downcast::<PyMapping>().is_err());
333337
assert!(list.as_ref().downcast::<PySequence>().is_ok());
334338
}
339+
340+
#[test]
341+
fn sequence_length() {
342+
Python::with_gil(|py| {
343+
let list = PyCell::new(
344+
py,
345+
OptionList {
346+
items: vec![Some(1), None],
347+
},
348+
)
349+
.unwrap();
350+
351+
assert_eq!(list.len().unwrap(), 2);
352+
assert_eq!(unsafe { ffi::PySequence_Length(list.as_ptr()) }, 2);
353+
354+
assert_eq!(unsafe { ffi::PyMapping_Length(list.as_ptr()) }, -1);
355+
unsafe { ffi::PyErr_Clear() };
356+
})
357+
}

tests/ui/invalid_pyclass_args.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,7 @@ struct InvalidModule {}
2121
#[pyclass(weakrev)]
2222
struct InvalidArg {}
2323

24+
#[pyclass(mapping, sequence)]
25+
struct CannotBeMappingAndSequence {}
26+
2427
fn main() {}

tests/ui/invalid_pyclass_args.stderr

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: expected one of: `crate`, `dict`, `extends`, `freelist`, `frozen`, `mapping`, `module`, `name`, `subclass`, `text_signature`, `unsendable`, `weakref`, `gc`
1+
error: expected one of: `crate`, `dict`, `extends`, `freelist`, `frozen`, `mapping`, `module`, `name`, `sequence`, `subclass`, `text_signature`, `unsendable`, `weakref`, `gc`
22
--> tests/ui/invalid_pyclass_args.rs:3:11
33
|
44
3 | #[pyclass(extend=pyo3::types::PyDict)]
@@ -34,8 +34,14 @@ error: expected string literal
3434
18 | #[pyclass(module = my_module)]
3535
| ^^^^^^^^^
3636

37-
error: expected one of: `crate`, `dict`, `extends`, `freelist`, `frozen`, `mapping`, `module`, `name`, `subclass`, `text_signature`, `unsendable`, `weakref`, `gc`
37+
error: expected one of: `crate`, `dict`, `extends`, `freelist`, `frozen`, `mapping`, `module`, `name`, `sequence`, `subclass`, `text_signature`, `unsendable`, `weakref`, `gc`
3838
--> tests/ui/invalid_pyclass_args.rs:21:11
3939
|
4040
21 | #[pyclass(weakrev)]
4141
| ^^^^^^^
42+
43+
error: a `#[pyclass]` cannot be both a `mapping` and a `sequence`
44+
--> tests/ui/invalid_pyclass_args.rs:25:8
45+
|
46+
25 | struct CannotBeMappingAndSequence {}
47+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)