On Feb 7, 2020, at 10:21, Todd email@example.com wrote:
I think it would be nice if pickle.dump and pickle.load would also accept a filename or path.
Pickle intentionally has the same API as marshal, and so do a number of other modules—not just in the stdlib, but popular third party modules. So, I don’t think you’d want to change pickle to be different from everything else, but it might be a major process to get everything changed.
Also, while there is code in Python that does this “file object or path” thing, I think it’s mostly older code, and not something to encourage going forward. It can be a confusing API, since there’s _other_ code that does the “file object or string” API (not too much of a problem for dump, but think about load). Maybe a keyword-only parameter would be better? Or even a third function: load for file, loads for string, loadp or load_path for path?
Or maybe it would be better to have a generic wrapper that can take any file-using function and give you a path-using function:
def opener(func, mode='r') @wraps(func) def wrapper(*args, **kw): with open(args[-1], mode) as f: return func(*args[:-1], f, **kwargs)
This seems a little magical to have in the stdlib (especially since obviously not every function that wants a file wants it as the last positional argument—in a different language I’d probably make this take the first argument and then wrap load in opener but dump in flip opener flip…), but might be worth putting in your own toolkit.