Replace mutable default arguments with None#43961
Replace mutable default arguments with None#43961DimiChatzipavlis wants to merge 1 commit intohuggingface:mainfrom
Conversation
|
[For maintainers] Suggested jobs to run (before merge) run-slow: idefics |
There was a problem hiding this comment.
Pull request overview
This PR fixes a common Python pitfall where mutable default arguments (specifically empty lists []) are shared across function calls, which can lead to unexpected behavior. The fix replaces these mutable defaults with None and initializes the list inside each function when needed.
Changes:
- Replaced mutable default argument
module_exceptions=[]withmodule_exceptions=Nonein three functions in the Idefics model - Replaced mutable default argument
trace_batch_nums=[]withtrace_batch_nums=Nonein theDebugUnderflowOverflowclass - Added appropriate
if Nonechecks inside each function to initialize empty lists
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| src/transformers/models/idefics/modeling_idefics.py | Updated freeze_model, freeze_text_layers, and freeze_vision_layers to use None as default with internal initialization |
| src/transformers/debug_utils.py | Updated DebugUnderflowOverflow.__init__ to use None as default for trace_batch_nums with internal initialization |
|
These methods are all very short and none of them mutate the input argument, though! I agree that it's an antipattern, which is why your code agent picked it up when asked to "improve the codebase" or however you prompted it, but it seems too insignificant to fix right now |
What does this PR do?
Fixes a common Python pitfall regarding mutable default arguments.
In Python, default arguments are evaluated only once at function definition time. If a mutable object (like a
list) is used as a default, that same list instance is shared across all calls to the function. This can lead to insidious bugs where the list grows unexpectedly between function calls or instances.Modifications
Refactored the following method signatures to use
Noneas the default value and initialize the list inside the function:src/transformers/models/idefics/modeling_idefics.py:freeze_model(..., module_exceptions=[])->module_exceptions=Nonefreeze_text_layers(..., module_exceptions=[])->module_exceptions=Nonefreeze_vision_layers(..., module_exceptions=[])->module_exceptions=Nonesrc/transformers/debug_utils.py:DebugUnderflowOverflow.__init__(..., trace_batch_nums=[])->trace_batch_nums=NoneVerification
None(if arg is None: arg = []).Who can review?
@sgugger
@amyeroberts
@ArthurZucker
Before submitting
Pull Request section?
to it if that's the case.
documentation guidelines, and
here are tips on formatting docstrings.