Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
* PyPy support by omerbenamram in [#393](https://github.com/PyO3/pyo3/pull/393)
* Have `PyModule` generate an index of its members (`__all__` list).
* Allow `slf: PyRef<T>` for pyclass(#419)
* Allow to use lifetime specifiers in `pymethods`
* Add `marshal` module. [#460](https://github.com/PyO3/pyo3/pull/460)

### Changed
Expand Down
14 changes: 12 additions & 2 deletions pyo3-derive-backend/src/pymethod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,18 @@ pub fn gen_py_method(
}

fn check_generic(name: &syn::Ident, sig: &syn::MethodSig) {
if !sig.decl.generics.params.is_empty() {
panic!("python method can not be generic: {:?}", name);
for param in &sig.decl.generics.params {
match param {
syn::GenericParam::Lifetime(_) => {}
syn::GenericParam::Type(_) => panic!(
"A Python method can't have a generic type parameter: {}",
name
),
syn::GenericParam::Const(_) => panic!(
"A Python method can't have a const generic parameter: {}",
name
),
}
}
}

Expand Down
30 changes: 29 additions & 1 deletion tests/test_methods.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict, PyString, PyTuple, PyType};
use pyo3::types::{IntoPyDict, PyDict, PyList, PySet, PyString, PyTuple, PyType};
use pyo3::PyRawObject;

#[macro_use]
Expand Down Expand Up @@ -306,3 +306,31 @@ fn meth_doc() {
)
.unwrap();
}

#[pyclass]
struct MethodWithLifeTime {}

#[pymethods]
impl MethodWithLifeTime {
fn set_to_list<'py>(&self, py: Python<'py>, set: &'py PySet) -> PyResult<&'py PyList> {
let mut items = vec![];
for _ in 0..set.len() {
items.push(set.pop().unwrap());
}
let list = PyList::new(py, items);
list.sort()?;
Ok(list)
}
}

#[test]
fn method_with_lifetime() {
let gil = Python::acquire_gil();
let py = gil.python();
let obj = PyRef::new(py, MethodWithLifeTime {}).unwrap();
py_run!(
py,
obj,
"assert obj.set_to_list(set((1, 2, 3))) == [1, 2, 3]"
);
}