Skip to content

pyopenms: Param to_dict quality of life improvements - #8631

Merged
timosachsenberg merged 5 commits into
developfrom
claude/param-dict-conversion-KRiM8
Jan 12, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
claude/param-dict-conversion-KRiM8

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jan 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

This pull request significantly enhances the Pythonic usability of the Param class in pyOpenMS, making it behave more like a standard Python dictionary. The changes introduce new methods for conversion between dictionaries and Param, add standard Python special methods for iteration and containment, and update the interface to accept both string and bytes keys. Comprehensive unit tests are also added to ensure correct behavior and backward compatibility.

Pythonic interface improvements:

  • Added a from_dict static method to the Param class, allowing creation of a Param object from a Python dictionary with string or bytes keys.
  • Added a to_dict method returning a dictionary with string keys, providing a more Pythonic alternative to the existing asDict method (which returns bytes keys for backward compatibility).
  • Implemented standard Python special methods: __iter__, __len__, and __contains__, enabling iteration over keys, length queries, and membership tests using both string and bytes keys.
  • Updated the get, __getitem__, and __setitem__ methods to accept both string and bytes keys, improving ergonomics and backward compatibility.
  • Updated the Cython definition (Param.pxd) to reflect the new and updated Pythonic methods.

Testing enhancements:

  • Added a comprehensive unit test testParamPythonicInterface to verify all new behaviors, including round-trips between dict and Param, key type flexibility, and compatibility with both string and bytes keys.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features

    • Param now provides a dictionary-like interface with from_dict() and to_dict() for easy conversion.
    • Pythonic container support: iteration, length, and key-existence checks.
    • Key access accepts both string and bytes for greater flexibility.
  • Tests

    • Added comprehensive tests covering the new Pythonic Param interface.

✏️ Tip: You can customize this high-level summary in your review settings.

- Add from_dict() static method to create Param from dictionary
- Add to_dict() as PEP 8 alias for asDict()
- Add __len__() for len(param) support
- Add __iter__() for direct iteration over keys
- Add __contains__() for 'key in param' syntax
- Accept both str and bytes keys in get/set operations
- Add comprehensive tests for new functionality
- to_dict() now returns {str: value} instead of {bytes: value}
- asDict() unchanged for backward compatibility (still returns bytes keys)
- Enables clean fetch-modify-update workflow:
    d = param.to_dict()
    d["key"] = new_value
    param.update(d)
- Add tests for round-trip workflow
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Note: this does not try to solve #8627

@coderabbitai

coderabbitai Bot commented Jan 11, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a Pythonic dict-like interface to the Param class: new from_dict()/to_dict() helpers, key normalization for str/bytes, container semantics (__iter__, __len__, __contains__), widened key-type signatures for get, __getitem__, __setitem__, and accompanying tests.

Changes

Cohort / File(s) Summary
Param API Declaration
src/pyOpenMS/pxds/Param.pxd
Updated signatures to accept flexible key types for get(), __getitem__(), __setitem__(). Added from_dict(d), to_dict(), __iter__(), __len__(), and __contains__() declarations.
Param Implementation
src/pyOpenMS/addons/Param.pyx
Implemented from_dict() (static), to_dict(), _to_bytes_key() helper, and container magic methods; widened key argument types for get, __getitem__, __setitem__; added keys(), items(), values(), descriptions(), and updated update() docstring.
Test Coverage
src/pyOpenMS/tests/unittests/test000.py
Added testParamPythonicInterface() validating dict construction/round-trip, mixed str/bytes key access, iteration, containment, asDict() compatibility, empty-Param behavior. Note: identical test block appears duplicated in the diff and may require deduplication.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hop through keys of bytes and string delight,
From dict I spring, to dict take flight—
I count, I iterate, I nestle in code,
Round-trip and return down the rabbit road,
A tiny Params warren, soft and bright.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly reflects the main change: adding dictionary-like quality of life improvements to the Param class, including from_dict(), to_dict(), and other Pythonic methods.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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


📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9c55cbd and 01a0438.

📒 Files selected for processing (1)
  • src/pyOpenMS/addons/Param.pyx
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4-space indentation for Python and Cython files per PEP 8; no tabs; Unix line endings (LF)

Files:

  • src/pyOpenMS/addons/Param.pyx
**

📄 CodeRabbit inference engine (AGENTS.md)

File extensions must be lowercase except for ML, XML, and mzData

Files:

  • src/pyOpenMS/addons/Param.pyx
src/pyOpenMS/addons/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/addons/*.pyx: Python addon methods must not be added to .pxd files; use src/pyOpenMS/addons/ or _dataframes.py wrappers instead
pyOpenMS addons must use 4-space indentation and maintain minimal code; avoid redundant aliases
Do not add custom __init__ methods in pyOpenMS unless required; it overrides autowrap dispatchers
Autowrap returns Python strings; do NOT call .decode() on autowrap string return values
Avoid cdef typed variables for autowrap return values inside def methods; use Python type checks instead
Regenerate pyOpenMS after addon changes by removing .cpp_extension_generated and rebuilding with --target pyopenms

Files:

  • src/pyOpenMS/addons/Param.pyx
src/pyOpenMS/**/*.{pyx,pxd,py}

📄 CodeRabbit inference engine (AGENTS.md)

Use snake_case for all Python-facing names and DataFrame column names in pyOpenMS

Files:

  • src/pyOpenMS/addons/Param.pyx
src/pyOpenMS/**/*.{pyx,py}

📄 CodeRabbit inference engine (AGENTS.md)

pyOpenMS DataFrame pattern: get_data_dict() in addon returns numpy arrays; get_df() in _dataframes.py wraps with pandas

Files:

  • src/pyOpenMS/addons/Param.pyx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-lnx
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-macos-arm
  • GitHub Check: build-win
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: cppcheck-test
🔇 Additional comments (10)
src/pyOpenMS/addons/Param.pyx (10)

4-22: LGTM!

Clean implementation that appropriately delegates to update(). The docstring clearly documents the flexible key types.


24-28: LGTM!

Good helper for key normalization. The pass-through for non-str types lets the C++ layer handle type validation, which is appropriate for a Cython wrapper.


44-52: LGTM!

Good backward-compatible approach. The docstring appropriately guides users to the PEP 8 compliant alternative while preserving existing behavior.


149-168: LGTM!

Proper implementation of dict-like get() behavior with flexible key types. The use of _to_bytes_key() ensures consistent key handling.


170-189: LGTM!

Standard dict-like access pattern with proper key normalization. The exception behavior for missing keys aligns with Python dict semantics.


191-212: LGTM - Enables dict-like creation of new parameters.

The logic correctly handles both existing keys (preserving metadata) and new keys (using sensible defaults). This enables from_dict() and update() to create new parameters as expected from dict-like interfaces. Users needing to set tags/description can still use the full setValue() API directly.


214-227: LGTM!

Iteration yields bytes keys for consistency with asDict() and backward compatibility. The flexible key acceptance in __getitem__ allows string-key access even though iteration produces bytes.


229-241: LGTM!

Clean implementation of the container protocol using the existing size() method.


243-260: LGTM!

Proper implementation of membership testing with flexible key types. The _to_bytes_key() normalization ensures both string and bytes keys work as expected.


54-76: The .decode('utf-8') call is appropriate and necessary here. The items() method signature explicitly returns List[Tuple[bytes, ...]], meaning keys are C++ bytes, not autowrap strings. This is different from the coding guideline restriction, which prohibits .decode() on autowrap string return values (which are already strings). The pattern is consistent with the existing __str__() method in the same file, which also decodes keys without error handling.

Likely an incorrect or invalid review comment.


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.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Before: bytes handling

d = param.asDict() # {b"key": value}
d[b"threshold"] = 0.75 # Must use bytes
param.update(d)

After: accepts strings

d = param.to_dict() # {"key": value}
d["threshold"] = 0.75 # Use strings
param.update(d) # Just works

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
src/pyOpenMS/addons/Param.pyx (1)

24-28: Consider adding type validation for unexpected key types.

The helper only checks for str, implicitly assuming anything else is already bytes. If a caller passes an unexpected type (e.g., int), it would be passed through unchanged and likely cause a confusing error later in the C++ layer.

Optional: Add explicit type checking
     def _to_bytes_key(self, key):
         """Convert a string or bytes key to bytes."""
         if isinstance(key, str):
             return key.encode('utf-8')
+        if not isinstance(key, bytes):
+            raise TypeError(f"key must be str or bytes, not {type(key).__name__}")
         return key
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 244eb32 and 9c55cbd.

📒 Files selected for processing (3)
  • src/pyOpenMS/addons/Param.pyx
  • src/pyOpenMS/pxds/Param.pxd
  • src/pyOpenMS/tests/unittests/test000.py
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4-space indentation for Python and Cython files per PEP 8; no tabs; Unix line endings (LF)

Files:

  • src/pyOpenMS/addons/Param.pyx
  • src/pyOpenMS/pxds/Param.pxd
  • src/pyOpenMS/tests/unittests/test000.py
**

📄 CodeRabbit inference engine (AGENTS.md)

File extensions must be lowercase except for ML, XML, and mzData

Files:

  • src/pyOpenMS/addons/Param.pyx
  • src/pyOpenMS/pxds/Param.pxd
  • src/pyOpenMS/tests/unittests/test000.py
src/pyOpenMS/addons/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/addons/*.pyx: Python addon methods must not be added to .pxd files; use src/pyOpenMS/addons/ or _dataframes.py wrappers instead
pyOpenMS addons must use 4-space indentation and maintain minimal code; avoid redundant aliases
Do not add custom __init__ methods in pyOpenMS unless required; it overrides autowrap dispatchers
Autowrap returns Python strings; do NOT call .decode() on autowrap string return values
Avoid cdef typed variables for autowrap return values inside def methods; use Python type checks instead
Regenerate pyOpenMS after addon changes by removing .cpp_extension_generated and rebuilding with --target pyopenms

Files:

  • src/pyOpenMS/addons/Param.pyx
src/pyOpenMS/**/*.{pyx,pxd,py}

📄 CodeRabbit inference engine (AGENTS.md)

Use snake_case for all Python-facing names and DataFrame column names in pyOpenMS

Files:

  • src/pyOpenMS/addons/Param.pyx
  • src/pyOpenMS/pxds/Param.pxd
  • src/pyOpenMS/tests/unittests/test000.py
src/pyOpenMS/**/*.{pyx,py}

📄 CodeRabbit inference engine (AGENTS.md)

pyOpenMS DataFrame pattern: get_data_dict() in addon returns numpy arrays; get_df() in _dataframes.py wraps with pandas

Files:

  • src/pyOpenMS/addons/Param.pyx
  • src/pyOpenMS/tests/unittests/test000.py
src/pyOpenMS/pxds/*.pxd

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/pxds/*.pxd: pyOpenMS .pxd files must declare default and copy constructors; use cimport instead of Python import
pyOpenMS .pxd files must use cdef cppclass ClassName: for non-inheriting classes without a base class
pyOpenMS .pxd signatures must stay synchronized with corresponding C++ API changes
pyOpenMS wrap-doc: formatting requires exactly # (hash + 2 spaces) for all documentation continuation lines; changing to # or # breaks parsing

Files:

  • src/pyOpenMS/pxds/Param.pxd
src/pyOpenMS/tests/**/*.py

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write pyOpenMS tests for new Python bindings

Files:

  • src/pyOpenMS/tests/unittests/test000.py
🧠 Learnings (3)
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/pyOpenMS/**/*.{pyx,py} : pyOpenMS DataFrame pattern: `get_data_dict()` in addon returns numpy arrays; `get_df()` in `_dataframes.py` wraps with pandas

Applied to files:

  • src/pyOpenMS/pxds/Param.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings

Applied to files:

  • src/pyOpenMS/tests/unittests/test000.py
📚 Learning: 2026-01-04T21:35:37.785Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8588
File: src/pyOpenMS/tests/unittests/test_TargetedQuantitation.py:1-456
Timestamp: 2026-01-04T21:35:37.785Z
Learning: For Python files in the repository, follow PEP 8: use 4-space indentation, avoid tabs, and ensure Unix LF line endings. The 2-space indentation and Unix line endings guideline applies to C/Cython in their respective languages; Python files should adhere to Python style (PEP 8) regardless of other language rules.

Applied to files:

  • src/pyOpenMS/tests/unittests/test000.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build-macos-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-win
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
🔇 Additional comments (6)
src/pyOpenMS/tests/unittests/test000.py (1)

1675-1789: Comprehensive test coverage for the new Pythonic interface.

The test function thoroughly validates:

  • from_dict() with both bytes and string keys
  • to_dict() returning string keys
  • asDict() backward compatibility with bytes keys
  • Container semantics (__len__, __iter__, __contains__)
  • Key access with mixed types (__getitem__, __setitem__, get())
  • Round-trip workflows
  • Empty Param handling

The tests are well-structured and cover the key use cases for the new dict-like interface.

src/pyOpenMS/pxds/Param.pxd (1)

17-31: Declaration additions align with the addon pattern.

The new Pythonic interface methods are correctly declared with # wrap-ignore comments, which ensures autowrap doesn't try to generate bindings for them since the implementations are provided in the addon file (Param.pyx). This follows the established pattern for other addon methods like asDict(), keys(), items(), etc.

src/pyOpenMS/addons/Param.pyx (4)

4-22: LGTM - Clean factory method implementation.

The from_dict static method provides a straightforward way to construct a Param from a dictionary. It correctly leverages the existing update() method which already handles both string and bytes keys.


54-76: Good implementation with clear documentation.

The to_dict() method provides the expected Pythonic interface returning string keys, while asDict() maintains backward compatibility with bytes keys. The docstring clearly explains the distinction and provides a useful example.


209-255: Clean implementation of Python container protocols.

The __iter__, __len__, and __contains__ methods correctly delegate to existing functionality while providing the expected Pythonic interface. The __contains__ method properly handles both string and bytes keys through _to_bytes_key.


191-207: The implementation is correct and requires no changes.

The __setitem__ method successfully handles both existing and new parameter keys. The passing test testParamPythonicInterface() demonstrates that setting a new key (p["new_param"] = 999) works without exceptions, contradicting the original concern that getTags() and getDescription() would fail on non-existent keys. The implementation is sound and works as intended.

When setting a parameter value with __setitem__, check if the key exists
before calling getTags() and getDescription(). If the key doesn't exist,
use empty defaults instead of throwing a RuntimeError.

This fixes the from_dict() and update() methods which create new
parameters that don't exist yet.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@jpfeuffer a bit easier to use. What do you think?

@jpfeuffer

Copy link
Copy Markdown
Contributor

Yes definitely. See my comments in the other issue for other quick wins.

@timosachsenberg
timosachsenberg merged commit b1d3a5d into develop Jan 12, 2026
@timosachsenberg
timosachsenberg deleted the claude/param-dict-conversion-KRiM8 branch January 12, 2026 07:03
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.

3 participants