Skip to content

Commit 7455518

Browse files
authored
Merge pull request #2031 from davidhewitt/resurrect-type-is-instance
pytype: resurrect (deprecated) PyType::is_instance
2 parents 770c02e + b56d492 commit 7455518

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3131
- `ptraceback` -> `traceback`
3232
- `from_instance` -> `from_value`
3333
- `into_instance` -> `into_value`
34+
- Deprecate `PyType::is_instance`; it is inconsistent with other `is_instance` methods in PyO3. Instead of `typ.is_instance(obj)`, use `obj.is_instance(typ)`. [#2031](https://github.com/PyO3/pyo3/pull/2031)
3435

3536
### Removed
3637

37-
- Remove `PyType::is_instance`, which is unintuitive; instead of `typ.is_instance(obj)`, use `obj.is_instance(typ)`. [#1985](https://github.com/PyO3/pyo3/pull/1985)
3838
- Remove all functionality deprecated in PyO3 0.14. [#2007](https://github.com/PyO3/pyo3/pull/2007)
3939

4040
### Fixed

src/types/typeobject.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,19 @@ impl PyType {
5959
{
6060
self.is_subclass(T::type_object(self.py()))
6161
}
62+
63+
#[deprecated(
64+
since = "0.16.0",
65+
note = "prefer obj.is_instance(type) to typ.is_instance(obj)"
66+
)]
67+
/// Equivalent to Python's `isinstance(obj, self)`.
68+
///
69+
/// This function has been deprecated because it has inverted argument ordering compared to
70+
/// other `is_instance` functions in PyO3 such as [`PyAny::is_instance`].
71+
pub fn is_instance<T: AsPyPointer>(&self, obj: &T) -> PyResult<bool> {
72+
let any: &PyAny = unsafe { self.py().from_borrowed_ptr(obj.as_ptr()) };
73+
any.is_instance(self)
74+
}
6275
}
6376

6477
#[cfg(test)]
@@ -84,4 +97,15 @@ mod tests {
8497
assert!(PyBool::type_object(py).is_subclass_of::<PyLong>().unwrap());
8598
});
8699
}
100+
101+
#[test]
102+
#[allow(deprecated)]
103+
fn type_is_instance() {
104+
Python::with_gil(|py| {
105+
let bool_object = PyBool::new(py, false);
106+
let bool_type = bool_object.get_type();
107+
assert!(bool_type.is_instance(bool_object).unwrap());
108+
assert!(bool_object.is_instance(bool_type).unwrap());
109+
})
110+
}
87111
}

0 commit comments

Comments
 (0)