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

Move Partial Serialization out of MSONable #744

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

jmmshn
Copy link
Contributor

@jmmshn jmmshn commented Feb 7, 2025

Move Partial Serialization out of MSONable

The mechanism to attempt to serialize objects and pkl the un-serializable parts is useful outside of MSONable.
Pulled the function out of MSONable and added a save function outside as well.

This should not change the behavior of existing code but should enable the ability to do the following

        is_m = GoodMSONClass(a=1, b=2, c=3)
        not_m = GoodNOTMSONClass(a="a", b="b", c="c")

        is_m_jsons, is_m_map = partial_monty_encode(is_m)
        is_m_d = json.loads(is_m_jsons)
        assert is_m_d["@class"] == "GoodMSONClass"
        assert is_m_d["a"] == 1
        assert len(is_m_map) == 0

        not_m_jsons, not_m_map = partial_monty_encode(not_m)
        not_m_d = json.loads(not_m_jsons)
        assert not_m_d["@class"] == "GoodNOTMSONClass"
        assert "@object_reference" in not_m_d
        assert len(not_m_map) == 1
        mixed = {"is_m": is_m, "not_m": not_m}
        mixed_jsons, mixed_map = partial_monty_encode(mixed, {"indent": 2})
        mixed_d = json.loads(mixed_jsons)
        assert mixed_d["is_m"]["a"] == 1
        assert mixed_d["is_m"]["@class"] == "GoodMSONClass"
        assert "@object_reference" in mixed_d["not_m"]
        assert mixed_d["not_m"]["@class"] == "GoodNOTMSONClass"

        mixed = {"is_m": is_m, "not_m": not_m}
        save(mixed, tmp_path / "mixed.json")
        loaded = load2dict(tmp_path / "mixed.json")
        assert loaded["is_m"]["a"] == 1
        assert loaded["not_m"].a == "a"

Summary by CodeRabbit

  • New Features
    • Enhanced JSON encoding and decoding now allow for seamless saving and loading by handling elements that aren’t directly serializable.
  • Tests
    • Introduced new test cases to ensure the improved serialization process reliably manages mixed data types and file operations.

Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

The pull request introduces significant changes to the JSON serialization functionality in the module. A new private method, _get_partial_json, is added to manage JSON representation with hash references for unserializable objects. This method is utilized by the newly introduced partial_monty_encode function, which processes objects and returns both the JSON encoding and a name-object map. The existing get_partial_json method is removed, and its logic is refactored into the new functions. Additionally, the save method is updated to streamline keyword argument initialization, and the load method is modified to utilize load2dict.

Changes

File(s) Change Summary
src/monty/json.py • Added _get_partial_json to handle JSON conversion with hash references.
• Introduced partial_monty_encode for processing objects and returning JSON with a name-object map.
• Removed get_partial_json and refactored its logic.
• Modified save to initialize json_kwargs and updated its signature.
• Updated load method to use load2dict instead of _d_from_path.
tests/test_json.py • Added test_partial_serializable to TestJson to validate partial_monty_encode functionality with MSONable and non-MSONable classes.

Possibly related PRs

  • Add support for extended JSON to MontyDecoder #729: The changes in the main PR focus on modifying JSON serialization methods in src/monty/json.py, while the retrieved PR enhances BSON and JSON decoding in the same file, indicating a direct relationship through the shared context of serialization and deserialization processes.
  • Add save and load functionality to MSONable #670: The changes in the main PR are related to the modifications in the partial_monty_encode function and the _get_partial_json method, which directly connect to the get_partial_json method introduced in the retrieved PR.

Poem

Hoppin' through the code I go,
New methods shining, watch them glow.
JSON sings with hash in tow,
Errors caught with a gentle throw.
I’m a rabbit, coding with cheer,
Celebrating changes far and near!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d85adf and 5a9f6b3.

📒 Files selected for processing (2)
  • src/monty/json.py (4 hunks)
  • tests/test_json.py (2 hunks)
🔇 Additional comments (5)
src/monty/json.py (4)

1092-1098: LGTM! Clean implementation of partial JSON serialization.

The function is well-scoped, follows single responsibility principle, and has clear parameters.


1101-1121: LGTM! Well-documented and properly typed implementation.

The function provides a clean public API for partial serialization with proper type hints and documentation.


358-402: LGTM! Clean delegation to standalone save function.

The method maintains backward compatibility while properly delegating to the new standalone implementation.


423-490: LGTM! Robust implementation of standalone save functionality.

The function properly handles:

  • Directory creation
  • File existence checks
  • Path handling using Path objects
  • Both JSON and pickle serialization
tests/test_json.py (1)

22-24: LGTM! Imports align with new functionality.

The imports correctly reflect the newly added functions.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/monty/json.py (2)

1052-1058: Improve docstring formatting and clarity.

The docstring could be improved by:

  • Using consistent formatting (e.g., Google style)
  • Adding parameter descriptions
  • Adding return value descriptions
-    """Used with the save method. Gets the json representation of a class
-    with the unserializable components sustituted for hash references."""
+    """Gets the JSON representation of a class with unserializable components substituted with hash references.
+
+    Args:
+        obj: Object to serialize
+        json_kwargs: Keyword arguments to pass to the JSON encoder
+
+    Returns:
+        tuple: (encoder, encoded, json_kwargs)
+            - encoder: MontyEncoder instance used for serialization
+            - encoded: JSON string representation
+            - json_kwargs: Keyword arguments used for serialization
+    """

1060-1084: Fix incorrect parameter documentation.

The docstring mentions an unused parameter pickle_kwargs.

-    """Encode an object that may contain unhashable parts.
-
-    Parameters
-    ----------
-    json_kwargs : dict
-        Keyword arguments to pass to the serializer.
-    pickle_kwargs : dict
-        Keyword arguments to pass to pickle.dump.
-
-    Returns
-    -------
-    str, dict
-        The json encoding of the class and the name-object map if one is
-        required, otherwise None.
-    """
+    """Encode an object that may contain unhashable parts.
+
+    Parameters
+    ----------
+    obj : Any
+        Object to encode
+    json_kwargs : dict, optional
+        Keyword arguments to pass to the serializer.
+
+    Returns
+    -------
+    str, dict
+        The json encoding of the class and the name-object map if one is
+        required, otherwise None.
+    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35ffd2d and 3f5da81.

📒 Files selected for processing (1)
  • src/monty/json.py (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, 3.13)
  • GitHub Check: build (windows-latest, 3.12)
  • GitHub Check: build (windows-latest, 3.11)
  • GitHub Check: build (windows-latest, 3.10)
  • GitHub Check: build (windows-latest, 3.9)
  • GitHub Check: build (ubuntu-latest, 3.12)
  • GitHub Check: build (ubuntu-latest, 3.11)
  • GitHub Check: build (ubuntu-latest, 3.10)
  • GitHub Check: build (ubuntu-latest, 3.9)
🔇 Additional comments (3)
src/monty/json.py (3)

358-375: LGTM! Clean refactoring of serialization logic.

The refactoring improves code organization by delegating the serialization logic to a dedicated function.


418-420: LGTM! Proper initialization of kwargs.

The initialization of kwargs with empty dictionaries prevents potential NoneType errors and follows best practices.


1020-1023: LGTM! Improved error handling.

The change to catch specific AttributeError follows Python's best practices for exception handling.

@jmmshn jmmshn changed the title [WIP] Partial Serialization [WIP] Move Partial Serialization out of MSONable Feb 7, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/monty/json.py (2)

1052-1058: Fix typo in docstring and remove unused return value.

  1. The docstring has a typo: "sustituted" should be "substituted"
  2. The function returns json_kwargs which is not used by the caller

Apply this diff to fix the issues:

-    """Used with the save method. Gets the json representation of a class
-    with the unserializable components sustituted for hash references."""
+    """Used with the save method. Gets the json representation of a class
+    with the unserializable components substituted for hash references."""
     encoder = MontyEncoder(allow_unserializable_objects=True, **json_kwargs)
     encoded = encoder.encode(obj)
-    return encoder, encoded, json_kwargs
+    return encoder, encoded

1060-1084: Fix incorrect parameter documentation.

The docstring mentions pickle_kwargs parameter but it's not used in the function.

Apply this diff to fix the docstring:

-    Parameters
-    ----------
-    json_kwargs : dict
-        Keyword arguments to pass to the serializer.
-    pickle_kwargs : dict
-        Keyword arguments to pass to pickle.dump.
+    Parameters
+    ----------
+    obj : object
+        The object to encode.
+    json_kwargs : dict, optional
+        Keyword arguments to pass to the serializer.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f5da81 and a616389.

📒 Files selected for processing (1)
  • src/monty/json.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: build (windows-latest, 3.12)
  • GitHub Check: build (windows-latest, 3.11)
  • GitHub Check: build (windows-latest, 3.10)
  • GitHub Check: build (windows-latest, 3.9)
  • GitHub Check: build (ubuntu-latest, 3.12)
  • GitHub Check: build (ubuntu-latest, 3.11)
  • GitHub Check: build (ubuntu-latest, 3.10)
  • GitHub Check: build (ubuntu-latest, 3.9)
🔇 Additional comments (2)
src/monty/json.py (2)

358-375: LGTM! Clean refactoring of get_partial_json.

The refactoring improves code organization by delegating the complex logic to a dedicated function while maintaining backward compatibility.


418-420: LGTM! Good defensive programming.

Initializing kwargs to empty dicts prevents NoneType errors and ensures consistent behavior.

Copy link

codecov bot commented Feb 7, 2025

Codecov Report

Attention: Patch coverage is 86.66667% with 4 lines in your changes missing coverage. Please review.

Project coverage is 84.91%. Comparing base (35ffd2d) to head (5a9f6b3).

Files with missing lines Patch % Lines
src/monty/json.py 86.66% 1 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #744      +/-   ##
==========================================
+ Coverage   84.75%   84.91%   +0.16%     
==========================================
  Files          27       27              
  Lines        1653     1651       -2     
  Branches      315      312       -3     
==========================================
+ Hits         1401     1402       +1     
+ Misses        192      191       -1     
+ Partials       60       58       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/monty/json.py (1)

1053-1059: Fix typo in docstring.

The method is well-focused and follows the single responsibility principle. However, there is a typo in the docstring.

-    with the unserializable components sustituted for hash references."""
+    with the unserializable components substituted for hash references."""
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a616389 and 5bd31ad.

📒 Files selected for processing (2)
  • src/monty/json.py (4 hunks)
  • tests/test_json.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/test_json.py

1146-1146: Pointless comparison. Did you mean to assign a value? Otherwise, prepend assert or remove it.

(B015)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, 3.13)
  • GitHub Check: build (windows-latest, 3.12)
  • GitHub Check: build (windows-latest, 3.11)
  • GitHub Check: build (windows-latest, 3.10)
  • GitHub Check: build (windows-latest, 3.9)
  • GitHub Check: build (ubuntu-latest, 3.12)
  • GitHub Check: build (ubuntu-latest, 3.11)
  • GitHub Check: build (ubuntu-latest, 3.10)
  • GitHub Check: build (ubuntu-latest, 3.9)
🔇 Additional comments (3)
src/monty/json.py (3)

358-376: LGTM! Clean refactoring of get_partial_json.

The method has been nicely refactored to delegate its logic to the new partial_monty_encode function while maintaining backward compatibility.


419-421: LGTM! Good defensive programming.

The initialization of json_kwargs and pickle_kwargs to empty dictionaries when None prevents potential NoneType errors.


1062-1082: LGTM! Well-documented and focused implementation.

The function is well-documented with clear docstrings and follows the single responsibility principle. The implementation correctly handles the encoding of objects with unhashable parts.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5bd31ad and 1ef8490.

📒 Files selected for processing (2)
  • src/monty/json.py (5 hunks)
  • tests/test_json.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_json.py
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/monty/json.py

[warning] 372-374: src/monty/json.py#L372-L374
Added lines #L372 - L374 were not covered by tests


[warning] 498-498: src/monty/json.py#L498
Added line #L498 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: codecov/patch
  • GitHub Check: build (windows-latest, 3.13)
  • GitHub Check: build (windows-latest, 3.12)
  • GitHub Check: build (windows-latest, 3.11)
  • GitHub Check: build (windows-latest, 3.10)
  • GitHub Check: build (windows-latest, 3.9)
  • GitHub Check: build (ubuntu-latest, 3.12)
  • GitHub Check: build (ubuntu-latest, 3.11)
  • GitHub Check: build (ubuntu-latest, 3.10)
  • GitHub Check: build (ubuntu-latest, 3.9)
🔇 Additional comments (3)
src/monty/json.py (3)

1110-1117: LGTM! Well-structured helper function.

The _get_partial_json function is well-designed as a private helper for JSON serialization with hash references.


1119-1140: LGTM! Clear and well-documented public API.

The partial_monty_encode function provides a clean interface for encoding objects with unhashable parts, with proper type hints and documentation.


372-374: Add test coverage for critical paths.

The following code paths need test coverage:

  1. get_partial_json return value handling (lines 372-374)
  2. File existence check in save method (line 498)

Would you like me to generate test cases for these scenarios? Here's what we should test:

  1. get_partial_json with empty name_object_map
  2. save with existing pickle file and strict=True

Also applies to: 498-498

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 372-374: src/monty/json.py#L372-L374
Added lines #L372 - L374 were not covered by tests

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/test_json.py (2)

1142-1146: Add version field verification.

The test verifies class name and value but doesn't check the version field which is a crucial part of MSONable objects.

         assert is_m_d["@class"] == "GoodMSONClass"
         assert is_m_d["a"] == 1
+        assert is_m_d["@version"] == TESTS_VERSION
         assert len(is_m_map) == 0

1161-1172: Clean up test file after use.

The test creates a file but doesn't clean it up after the test completes. This could lead to test pollution.

         save(mixed, tmp_path / "mixed.json", strict=False)
+        (tmp_path / "mixed.json").unlink()  # Clean up the test file
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ef8490 and 2d85adf.

📒 Files selected for processing (1)
  • tests/test_json.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: build (windows-latest, 3.12)
  • GitHub Check: build (windows-latest, 3.11)
  • GitHub Check: build (windows-latest, 3.10)
  • GitHub Check: build (windows-latest, 3.9)
  • GitHub Check: build (ubuntu-latest, 3.12)
  • GitHub Check: build (ubuntu-latest, 3.11)
  • GitHub Check: build (ubuntu-latest, 3.9)
🔇 Additional comments (3)
tests/test_json.py (3)

22-24: LGTM!

The new imports are correctly ordered and align with the functionality being tested.


1146-1146: Fix missing assertion.

The test coverage is comprehensive, testing both MSONable and non-MSONable objects. However, there is a missing assertion on line 1146.

-        len(is_m_map) == 0
+        assert len(is_m_map) == 0

1138-1172: LGTM! Comprehensive test coverage.

The test method provides thorough coverage of the partial serialization functionality:

  • Tests MSONable object serialization
  • Tests non-MSONable object serialization with object references
  • Tests mixed object serialization
  • Tests file operations with proper error handling

@jmmshn jmmshn changed the title [WIP] Move Partial Serialization out of MSONable Move Partial Serialization out of MSONable Feb 8, 2025
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