⚡️ Speed up function register_datatree_accessor by 7%
#10
+3
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 7% (0.07x) speedup for
register_datatree_accessorinxarray/datatree_/datatree/extensions.py⏱️ Runtime :
17.4 microseconds→16.2 microseconds(best of126runs)📝 Explanation and details
The optimization replaces
hasattr(cls, name)withgetattr(cls, name, None)and checks if the result isNoneinstead. This is a micro-optimization that reduces attribute lookup overhead in Python.Key changes:
hasattr(cls, name)toexisting = getattr(cls, name, None)followed byif existing is not None:hasattrinternally performs the same operation asgetattrbut then discards the valueWhy this is faster:
In Python,
hasattr(cls, name)internally callsgetattr(cls, name)and catches anyAttributeError. When an attribute doesn't exist,hasattrperforms the lookup, gets an exception, catches it, and returnsFalse. The optimized version usesgetattr(cls, name, None)which avoids exception handling entirely when the attribute doesn't exist - it simply returnsNone.Performance impact:
The 7% speedup (17.4μs → 16.2μs) comes from avoiding Python's exception handling machinery in the common case where no attribute conflict exists. This optimization is most beneficial when registering accessors on classes that don't already have the target attribute name, which appears to be the typical use case based on the test results.
Workload impact:
Based on the function references showing this is used in DataTree accessor registration tests, this optimization will benefit any code that frequently registers new accessors, particularly in testing scenarios or library initialization where multiple accessors are registered sequentially. The performance gain scales with the frequency of accessor registration calls.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-register_datatree_accessor-mi9q4c5eand push.