Why this matters
Using mutable objects as default arguments can lead to unexpected behavior since the same object is shared across function calls. Use None as a default and initialize the object inside the function.
Detect function definitions that use mutable objects (lists, dictionaries) as default arguments. This can lead to unintended shared state. Recommend using None as the default and initializing the object inside the function.
Using mutable objects as default arguments can lead to unexpected behavior since the same object is shared across function calls. Use None as a default and initialize the object inside the function.
Side-by-side examples engineers can pattern-match during review.
def add_item_to_list(item, my_list=[]):
my_list.append(item)
return my_list
def add_item_to_list(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.