Skip to content

serialization to json#12

Merged
ymahlau merged 10 commits into
mainfrom
develop
Apr 24, 2026
Merged

serialization to json#12
ymahlau merged 10 commits into
mainfrom
develop

Conversation

@ymahlau

@ymahlau ymahlau commented Apr 24, 2026

Copy link
Copy Markdown
Owner

resolves #6

Summary by CodeRabbit

Release Notes

  • New Features

    • Added serialization functionality to convert dataclass instances to and from JSON-compatible formats.
    • Enhanced attribute-setting methods with new parameters for controlling callback execution and modifying private fields.
  • Behavior Changes

    • Slot-based dataclass configuration is no longer supported.

@coderabbitai

coderabbitai Bot commented Apr 24, 2026

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

The PR adds serialization capabilities (to_dict, from_dict, to_json, from_json) to convert dataclass instances and JAX/NumPy arrays to/from JSON, enhances DataClass.aset with callback and private field control, disables slots-based dataclass support, and includes comprehensive test coverage for all new functionality.

Changes

Cohort / File(s) Summary
Serialization Implementation
src/drinx/serialize.py
New module with recursive encode/decode logic for primitives, tuples, dicts, JAX/NumPy arrays (with dtype/shape metadata), and dataclass instances; includes validation for field access and module imports during deserialization.
Public API Export
src/drinx/__init__.py
Exports serialization helpers (to_dict, from_dict, to_json, from_json) in __all__ for direct import from drinx.
DataClass Core Enhancements
src/drinx/base.py
Adds allow_private, bypass_callbacks to aset; introduces create_new_ok, bypass_callbacks to aset_inplace; adds _copy_and_set static helper; replaces dataclasses.replace logic; forces slots=False, weakref_slot=False in subclass decorator.
Decorator & Transform Updates
src/drinx/transform.py
Disables slots support by explicitly forcing slots=False, weakref_slot=False; adds AttributeError handling in flatten_with_keys with clearer error messages.
Visualization Minor Fix
src/drinx/visualize.py
Simplifies dtype/shape prefix formatting by using single-line generator expression in f-string.
Test Coverage for Serialization
tests/test_serialize.py
Comprehensive test suite (+760 lines) validating round-trip serialization: primitive types, tuple/dict tagging, JAX/NumPy arrays with dtype/shape, dataclass metadata, nested structures, error cases, and public API exposure.
Enhanced aset Tests
tests/test_base.py
Adds +481 lines of test coverage for allow_private, bypass_callbacks, create_new_ok parameters; validates callback execution control, private field mutations, and regression cases for unset fields.
Slots Test Removal
tests/test_dataclass.py
Removes 9 lines of @dataclass(slots=True) test coverage from TestSlots, retaining only default (non-slots) validation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PublicAPI as Public API<br/>(to_dict/from_dict)
    participant Serializer as Serializer<br/>(_serialize)
    participant Validator as Validator<br/>(Module Import)
    participant Deserializer as Deserializer<br/>(_deserialize)
    participant Constructor as DataClass<br/>Constructor

    Client->>PublicAPI: to_dict(obj)
    PublicAPI->>Serializer: _serialize(obj)
    Serializer->>Serializer: Check type (primitive/array/dataclass)
    alt JAX/NumPy Array
        Serializer->>Serializer: Extract dtype, shape, data
        Serializer-->>PublicAPI: {__jax__/numpy, dtype, shape, data}
    else Dataclass Instance
        Serializer->>Serializer: Get __module__, __name__
        Serializer->>Serializer: Filter init=True fields
        Serializer->>Serializer: Recursively serialize values
        Serializer-->>PublicAPI: {__module__, __name__, __value__}
    else Primitive/Collection
        Serializer-->>PublicAPI: JSON-safe structure
    end
    PublicAPI-->>Client: dict

    Client->>PublicAPI: from_dict(data)
    PublicAPI->>Validator: Validate markers & structure
    Validator->>Validator: Import module by name
    Validator->>Validator: Locate dataclass type
    PublicAPI->>Deserializer: _deserialize(data)
    Deserializer->>Deserializer: Reconstruct nested objects
    Deserializer->>Constructor: Instantiate with fields
    Constructor-->>Deserializer: instance
    Deserializer-->>PublicAPI: reconstructed object
    PublicAPI-->>Client: obj
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • aset for private attributes #11: Makes identical DataClass modifications (allow_private/bypass_callbacks additions to aset/aset_inplace, _copy_and_set helper, forced slots=False/weakref_slot=False), suggesting overlapping feature development.

Poem

🐰 Hop into serialization's glow,
DataClasses now have callbacks to flow!
Arrays and dicts, all tagged with care,
Slots be gone—simplicity everywhere! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: adding JSON serialization functionality to the drinx package.
Linked Issues check ✅ Passed The PR fulfills all requirements from issue #6: adds serialization helper functions (to_dict, from_dict, to_json, from_json) and supports serialization of both static and non-static/private dataclass fields.
Out of Scope Changes check ✅ Passed All changes align with the serialization objective. Supporting updates to base.py and transform.py are necessary for serialization functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.09589% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.90%. Comparing base (fa3bc32) to head (211a070).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/drinx/base.py 81.25% 5 Missing and 4 partials ⚠️
src/drinx/transform.py 75.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #12      +/-   ##
==========================================
+ Coverage   86.47%   87.90%   +1.43%     
==========================================
  Files           6        7       +1     
  Lines         451      587     +136     
  Branches       96      137      +41     
==========================================
+ Hits          390      516     +126     
- Misses         39       46       +7     
- Partials       22       25       +3     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ymahlau ymahlau merged commit ff241a4 into main Apr 24, 2026
2 of 3 checks passed
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.

Serialization

2 participants