This rule raises an issue when default_factory is incorrectly supplied as a keyword argument during the initialization of
collections.defaultdict.
The collections.defaultdict class provides a dictionary-like structure that calls a factory function to supply missing values. This
factory function (like list, int, or a lambda) is specified during initialization.
Crucially, the defaultdict constructor signature requires the default_factory as its first positional
argument. Any subsequent positional or keyword arguments are used to initialize the contents of the dictionary. This mirrors the behavior of
the standard dict constructor.
Providing the factory using the keyword default_factory=…, as in defaultdict(default_factory=list), is therefore
incorrect and leads to unexpected behavior:
defaultdict behaves like a regular dict in
this regard and will raise a KeyError when a missing key is accessed. {'default_factory': list}. To fix this issue correctly initialize the defaultdict with a default factory by providing the factory callable as the first
positional argument, not as a keyword argument.
from collections import defaultdict d1 = defaultdict(default_factory=int) # Noncompliant: this creates a dictionary with a single key-value pair.
from collections import defaultdict d1 = defaultdict(int) # Compliant