Add a CookieJar.get_cookie method

The cookie jar offers methods for writing (set_cookie, clear), but there’s no high level way to reading any of it i.e. no get_cookie.

Given a cookie jar jar, if one wanted to read the cookies, they’d need to iterate over it:

for cookie in jar:
    ...

Getting a specific cookie only adds to that (assuming a cookie set with domain, path, name):

for cookie in jar:
    if cookie.name == name:
        if cookie.domain == domain:
            if cookie.path == path:
                ...

An alternative is to access the underlying dictionary:

jar._cookies[domain][path][name]

In my particular case, I need to check cookies in unit tests (that e.g. they’re set correctly etc). While I can (and do) read from ._cookies, I’m always wary of accessing _ attributes - it feels like I’m doing something I shouldn’t. A very simple implementation would just officialize it:

    def get_cookie(domain: str, path: str, name: str) -> Cookie:
        return self._cookies[domain][path][name]

Things to consider:

  • what to do when the desired cookie doesn’t exist; e.g. KeyError works for me;
  • whether domain and path should be optional;
  • …which could then lead to a situation when there are multiple cookies with the same name (but different domains, paths).

If this is of interest, I can open a PR etc.

GH issue: Add a `CookieJar.get_cookie` method · Issue #104019 · python/cpython · GitHub

2 Likes

I’m unfamiliar with the library in question, but I think I understand what you’re talking about well enough to comment. What you describe sounds good.

Agreed; I can’t see a reason to complicate this.

They should definitely not be optional. Trying to do this with only a cookie name provided is a “searching” task, not simply direct access of a value. It should use a separate function, and then it can easily just return a list of everything that matches. It might have some more bells and whistles, too; that’s where the actual design work starts IMO.