From 0b5cbea68e47252efc3f0576fdea8817680747d3 Mon Sep 17 00:00:00 2001 From: Quaylyn Rimer Date: Thu, 17 Jul 2025 18:41:59 -0600 Subject: [PATCH] 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 --- rest_framework/filters.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 3f4730da84..010c87374f 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -249,7 +249,9 @@ def get_default_ordering(self, view): return (ordering,) return ordering - def get_default_valid_fields(self, queryset, view, context={}): + def get_default_valid_fields(self, queryset, view, context=None): + if context is None: + context = {} # If `ordering_fields` is not specified, then we determine a default # based on the serializer class, if one exists on the view. if hasattr(view, 'get_serializer_class'): @@ -286,7 +288,9 @@ def get_default_valid_fields(self, queryset, view, context={}): ) ] - def get_valid_fields(self, queryset, view, context={}): + def get_valid_fields(self, queryset, view, context=None): + if context is None: + context = {} valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) if valid_fields is None: pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy