-
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
Adds json_count_leaves
utility function
#23899
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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a json_count_leaves
utility function to count leaf elements in nested JSON-like structures and integrates it into the multimodal cache system for enhanced debugging. The implementation is clean and comes with a comprehensive set of unit tests. My main feedback is to improve the robustness of the new json_count_leaves
function by switching from a recursive to an iterative implementation. This will prevent potential RecursionError
exceptions when dealing with very deeply nested data structures.
|
||
def json_count_leaves(value: JSONTree[_T]) -> int: | ||
"""Count the number of leaves in a nested JSON structure.""" | ||
return sum(1 for _ in json_iter_leaves(value)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation uses json_iter_leaves
, which is recursive. This can lead to a RecursionError
for deeply nested JSON structures (the default limit in Python is often 1000). To make this utility function more robust, an iterative approach using an explicit stack is recommended. This avoids the recursion limit and is generally safer for functions processing arbitrary tree-like data structures.
return sum(1 for _ in json_iter_leaves(value)) | |
count = 0 | |
stack = [value] | |
while stack: | |
node = stack.pop() | |
if isinstance(node, dict): | |
stack.extend(node.values()) | |
elif isinstance(node, (list, tuple)): | |
stack.extend(node) | |
else: | |
count += 1 | |
return count |
Thanks, can you fix pre-commit? |
…ested JSON structures, integrated into multimodal cache for enhanced debugging
Signed-off-by: aditchawdhary <[email protected]>
Purpose
Add
json_count_leaves
utility function to count leaf elements in nested JSON structures, with integration into multimodal cache system for enhanced debugging capabilities.Test Plan
Test Result
Changes made:
Example usage:
supported_models.md
andexamples
for a new model.