diff --git a/src/requests/models.py b/src/requests/models.py index c4b25fa079..4e38f86ae5 100644 --- a/src/requests/models.py +++ b/src/requests/models.py @@ -119,8 +119,15 @@ def _encode_params(data): elif hasattr(data, "__iter__"): result = [] for k, vs in to_key_val_list(data): - if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): + if isinstance(vs, (str, bytes)) or not hasattr(vs, '__iter__'): vs = [vs] + + # --- START FIX --- + # If vs is an empty list [], treat it as [''] so it yields one empty key + if not vs: + vs = [''] + # --- END FIX --- + for v in vs: if v is not None: result.append( diff --git a/tests/test_requests.py b/tests/test_requests.py index 75d2deff2e..71a589bb14 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -119,6 +119,21 @@ def test_basic_building(self): assert pr.url == req.url assert pr.body == "life=42" + def test_params_with_empty_list_are_included(self): + """ + Regression test for #6557: Ensure empty lists in params + result in the key being present in the URL (e.g. key=). + """ + url = 'http://example.com' + params = {'key': []} + req = requests.Request('GET', url, params=params) + prep = req.prepare() + + # Check if the key is present with an empty value + assert 'key=' in prep.url + # Check that it didn't literally print the brackets + assert 'key=[]' not in prep.url + @pytest.mark.parametrize("method", ("GET", "HEAD")) def test_no_content_length(self, httpbin, method): req = requests.Request(method, httpbin(method.lower())).prepare()