fix: avoid mutable input kwargs defaults#10576
Conversation
There was a problem hiding this comment.
Code Review
This pull request resolves a common Python issue by replacing mutable default dictionary arguments ({}) with None for input_kwargs across several methods in HuggingfaceEngine, and adds a unit test to verify this behavior. The reviewer suggests a further improvement: instead of using input_kwargs = input_kwargs or {}, a shallow copy should be created (e.g., input_kwargs.copy()) to prevent mutating the caller's original dictionary when .pop() is called on it.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| input_kwargs: Optional[dict[str, Any]] = {}, | ||
| input_kwargs: Optional[dict[str, Any]] = None, | ||
| ) -> tuple[dict[str, Any], int]: | ||
| input_kwargs = input_kwargs or {} |
There was a problem hiding this comment.
Mutating input_kwargs via .pop() directly modifies the dictionary passed by the caller, which can lead to unexpected side effects if the caller reuses the dictionary. It is safer to create a shallow copy of the dictionary.
| input_kwargs = input_kwargs or {} | |
| input_kwargs = input_kwargs.copy() if input_kwargs else {} |
| input_kwargs: Optional[dict[str, Any]] = {}, | ||
| input_kwargs: Optional[dict[str, Any]] = None, | ||
| ) -> list[float]: | ||
| input_kwargs = input_kwargs or {} |
There was a problem hiding this comment.
Mutating input_kwargs via .pop() directly modifies the dictionary passed by the caller, which can lead to unexpected side effects if the caller reuses the dictionary. It is safer to create a shallow copy of the dictionary.
| input_kwargs = input_kwargs or {} | |
| input_kwargs = input_kwargs.copy() if input_kwargs else {} |
Summary
Removes the shared mutable
{}defaults from the HuggingFace chat engine helpers._process_args()and_get_scores()both consumeinput_kwargswith.pop(). With{}as the function default, calls that omittedinput_kwargsshared the same dict object. This patch changes the four HuggingfaceEngine helper signatures to default toNoneand normalizes to a fresh dict in the two helpers that pop values.Closes #10476.
To verify
PYTHONPATH=src python -m pytest tests\chat\test_hf_engine.py -qpython -m py_compile src\llamafactory\chat\hf_engine.py tests\chat\test_hf_engine.pypython -m ruff check src\llamafactory\chat\hf_engine.py tests\chat\test_hf_engine.pygit diff --check