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

Faster attribute lookup #943

Merged
merged 2 commits into from
Feb 20, 2025
Merged

Faster attribute lookup #943

merged 2 commits into from
Feb 20, 2025

Conversation

wjakob
Copy link
Owner

@wjakob wjakob commented Feb 20, 2025

When an attribute lookup fails, Python spends a significant chunk of CPU cycles formatting and then raising an exception.

The nb::getattr(object, key, default) API provides a fallback default value in the case of an error. The expense of raising an exception is therefore not wanted here.

This commit avoids this exception by

  • using the new PyObject_GetOptionalAttr() function on Python 3.13+
  • using an internal _PyObject_LookupAttr() API before Python 3.13.
  • on the 3.12 stable API, using PyObject_HasAttr() before doing the lookup.

@wjakob wjakob force-pushed the attr-lookup branch 2 times, most recently from d202ea3 to 779b2ec Compare February 20, 2025 15:18
When an attribute lookup fails, Python spends a significant chunk of CPU
cycles formatting and then raising an exception.

The ``nb::getattr(object, key, default)`` API provides a fallback
``default`` value in the case of an error. The expense of raising an
exception is therefore not wanted here.

This commit avoids this exception by

- using the new ``PyObject_GetOptionalAttr()`` function on Python 3.13+
- using an internal ``_PyObject_LookupAttr()`` API before Python 3.13.
- on the 3.12 stable API, using ``PyObject_HasAttr()`` before doing the lookup.
@wjakob wjakob merged commit c4a10ea into master Feb 20, 2025
34 checks passed
@wjakob wjakob deleted the attr-lookup branch February 20, 2025 15:42
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.

1 participant