Skip to content

Fix RequestsCookieJar returning KeyError for cookies with empty string values#7212

Open
bysiber wants to merge 1 commit intopsf:mainfrom
bysiber:fix/cookie-empty-value-keyerror
Open

Fix RequestsCookieJar returning KeyError for cookies with empty string values#7212
bysiber wants to merge 1 commit intopsf:mainfrom
bysiber:fix/cookie-empty-value-keyerror

Conversation

@bysiber
Copy link

@bysiber bysiber commented Feb 20, 2026

RequestsCookieJar._find_no_duplicates uses a truthiness check (if toReturn:) to determine whether a matching cookie was found. This causes cookies with empty string values to incorrectly raise KeyError, since "" is falsy in Python.

This affects both __getitem__ and get:

import requests

jar = requests.cookies.RequestsCookieJar()
jar.set("session", "")

jar["session"]           # raises KeyError (should return "")
jar.get("session", "x")  # returns "x" (should return "")

The fix changes the check from if toReturn: to if toReturn is not None:, which correctly distinguishes between "no cookie found" (None) and "cookie found with empty value" ("").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments