Skip to content

Commit 0b5cbea

Browse files
Fix mutable default arguments in OrderingFilter methods
- Fixed get_default_valid_fields() and get_valid_fields() methods in filters.py - Changed context={} default parameter to context=None to prevent mutable default anti-pattern - Added proper None checking with context = {} assignment inside methods Why this fix is important: - Mutable default arguments (context={}) create shared state across function calls - Same dict object gets reused, potentially causing unexpected side effects - This is a well-known Python anti-pattern that can lead to bugs What was changed: - Line 249: get_default_valid_fields(self, queryset, view, context=None) - Line 285: get_valid_fields(self, queryset, view, context=None) - Added 'if context is None: context = {}' in both methods Testing results: - All existing filter tests pass (pytest tests/test_filters.py) - Custom verification script confirms fix works correctly - Maintains backward compatibility - No breaking changes to API Addresses GitHub issue #9741
1 parent 2ae8c11 commit 0b5cbea

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

rest_framework/filters.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,9 @@ def get_default_ordering(self, view):
249249
return (ordering,)
250250
return ordering
251251

252-
def get_default_valid_fields(self, queryset, view, context={}):
252+
def get_default_valid_fields(self, queryset, view, context=None):
253+
if context is None:
254+
context = {}
253255
# If `ordering_fields` is not specified, then we determine a default
254256
# based on the serializer class, if one exists on the view.
255257
if hasattr(view, 'get_serializer_class'):
@@ -286,7 +288,9 @@ def get_default_valid_fields(self, queryset, view, context={}):
286288
)
287289
]
288290

289-
def get_valid_fields(self, queryset, view, context={}):
291+
def get_valid_fields(self, queryset, view, context=None):
292+
if context is None:
293+
context = {}
290294
valid_fields = getattr(view, 'ordering_fields', self.ordering_fields)
291295

292296
if valid_fields is None:

0 commit comments

Comments
 (0)