Http.cookiejar: support file-like objects for FileCookieJar and its sub-classes

Currently, http.cookiejar only supports path-like objects for FileCookieJar and its sub-classes (MozillaCookieJar and LWPCookieJar). So there’s no clean way to load interoperable cookie format data other than from the disk.

Reasoning:

  • Cookie files can contain sensitive info, so you may not want to write it to disk.
  • Its useful to provide the user other options to load data, other than from the disk, especially with keys/“secrets” (which cookies can contain). E.g. environment variable or standard input.
  • As I understand it, its preferable for python libraries to support file-like objects rather than just paths, when the path itself is not relevant (as in this case - http.cookiejar only uses for error messages for failing to load the path).

Workarounds:

  • Using the private function _really_load (not desirable as its a private function)
  • Making a fork of http.cookiejar (not desirable as it requires maintenance and this appears to require a small change to the http.cookiejar code)

What would it mean to provide a file-like object? Would that simply load the cookies but not save? None of the rest of your post refers to being able to mutate the cookie jar, but I’m not certain if that’s your intention here.

An unsaveable cookie jar subclass that can be given an existing file’s contents would seem like a useful feature. But if it needs to be able to save back afterwards, that’d be more complicated.

You can read from and write to the same file-like object by adding the + mode: Built-in functions — Python 3.15.0 documentation