Repository navigation
pyopenms: Param to_dict quality of life improvements - #8631
Conversation
- 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
|
Note: this does not try to solve #8627 |
📝 WalkthroughWalkthroughAdds a Pythonic dict-like interface to the Param class: new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 📜 Recent review detailsConfiguration used: Organization UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (5)**/*.{py,pyx,pxd}📄 CodeRabbit inference engine (AGENTS.md)
Files:
**📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/pyOpenMS/addons/*.pyx📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/pyOpenMS/**/*.{pyx,pxd,py}📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/pyOpenMS/**/*.{pyx,py}📄 CodeRabbit inference engine (AGENTS.md)
Files:
⏰ 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)
🔇 Additional comments (10)
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. Comment |
Before: bytes handlingd = param.asDict() # {b"key": value} After: accepts stringsd = param.to_dict() # {"key": value} |
There was a problem hiding this comment.
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 alreadybytes. 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
📒 Files selected for processing (3)
src/pyOpenMS/addons/Param.pyxsrc/pyOpenMS/pxds/Param.pxdsrc/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.pyxsrc/pyOpenMS/pxds/Param.pxdsrc/pyOpenMS/tests/unittests/test000.py
**
📄 CodeRabbit inference engine (AGENTS.md)
File extensions must be lowercase except for
ML,XML, andmzData
Files:
src/pyOpenMS/addons/Param.pyxsrc/pyOpenMS/pxds/Param.pxdsrc/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.pxdfiles; usesrc/pyOpenMS/addons/or_dataframes.pywrappers 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
Avoidcdeftyped variables for autowrap return values insidedefmethods; use Python type checks instead
Regenerate pyOpenMS after addon changes by removing.cpp_extension_generatedand 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.pyxsrc/pyOpenMS/pxds/Param.pxdsrc/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.pywraps with pandas
Files:
src/pyOpenMS/addons/Param.pyxsrc/pyOpenMS/tests/unittests/test000.py
src/pyOpenMS/pxds/*.pxd
📄 CodeRabbit inference engine (AGENTS.md)
src/pyOpenMS/pxds/*.pxd: pyOpenMS.pxdfiles must declare default and copy constructors; usecimportinstead of Pythonimport
pyOpenMS.pxdfiles must usecdef cppclass ClassName:for non-inheriting classes without a base class
pyOpenMS.pxdsignatures must stay synchronized with corresponding C++ API changes
pyOpenMSwrap-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 keysto_dict()returning string keysasDict()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-ignorecomments, 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 likeasDict(),keys(),items(), etc.src/pyOpenMS/addons/Param.pyx (4)
4-22: LGTM - Clean factory method implementation.The
from_dictstatic method provides a straightforward way to construct aParamfrom a dictionary. It correctly leverages the existingupdate()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, whileasDict()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 testtestParamPythonicInterface()demonstrates that setting a new key (p["new_param"] = 999) works without exceptions, contradicting the original concern thatgetTags()andgetDescription()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]>
|
@jpfeuffer a bit easier to use. What do you think? |
|
Yes definitely. See my comments in the other issue for other quick wins. |
Description
This pull request significantly enhances the Pythonic usability of the
Paramclass inpyOpenMS, making it behave more like a standard Python dictionary. The changes introduce new methods for conversion between dictionaries andParam, 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:
from_dictstatic method to theParamclass, allowing creation of aParamobject from a Python dictionary with string or bytes keys.to_dictmethod returning a dictionary with string keys, providing a more Pythonic alternative to the existingasDictmethod (which returns bytes keys for backward compatibility).__iter__,__len__, and__contains__, enabling iteration over keys, length queries, and membership tests using both string and bytes keys.get,__getitem__, and__setitem__methods to accept both string and bytes keys, improving ergonomics and backward compatibility.Param.pxd) to reflect the new and updated Pythonic methods.Testing enhancements:
testParamPythonicInterfaceto verify all new behaviors, including round-trips between dict andParam, key type flexibility, and compatibility with both string and bytes keys.Checklist
How can I get additional information on failed tests during CI
Click to expand
If your PR is failing you can check outIf you click in the column that lists the failed tests you will get detailed error messages.
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.rebuild jenkinswill retrigger Jenkins-based CI buildsSummary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.