Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pyany: add is_instance #1276

Merged
merged 1 commit into from
Nov 22, 2020
Merged

Conversation

davidhewitt
Copy link
Member

@davidhewitt davidhewitt commented Nov 15, 2020

Adds PyAny::is_instance::<T>().

This is an alternative to Python::is_instance() which offers slightly nicer syntax. I think there's a good consistency argument to adding this:

  • We expose other builtins like dir(), hash(), len() as PyAny::dir instead of Python::dir - is_instance has been a special case.
  • It's also consistent with PyErr::is_instance::<T>(py).

To encourage only one way to do things, I'm very tempted to mark #[deprecated] on Python::is_instance and Python::is_subclass (which is already redundant to PyType::is_subclass). What do you think of this?

Comparing from the documentation:

Python::is_instance:

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    assert!(py.is_instance::<PyBool, _>(PyBool::new(py, true)).unwrap());
    let list = PyList::new(py, &[1, 2, 3, 4]);
    assert!(!py.is_instance::<PyBool, _>(list).unwrap());
    assert!(py.is_instance::<PyList, _>(list).unwrap());
}

PyAny::is_instance:

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    assert!(PyBool::new(py, true).is_instance::<PyBool>().unwrap());
    let list = PyList::new(py, &[1, 2, 3, 4]);
    assert!(!list.is_instance::<PyBool>().unwrap());
    assert!(list.is_instance::<PyList>().unwrap());
}

@davidhewitt
Copy link
Member Author

cc @kngwyu - as this is a new public API that would be added to PyAny, I'd like to check you're ok with this before I merge.

@kngwyu
Copy link
Member

kngwyu commented Nov 20, 2020

Nice catch, thanks.

I'm very tempted to mark #[deprecated] on Python::is_instance and Python::is_subclass

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants