From 8885ac33e2b452bb52763d53933dc471ceb1a032 Mon Sep 17 00:00:00 2001 From: Edgar Costa Date: Tue, 14 Oct 2025 17:30:00 -0400 Subject: [PATCH] Enable save/load to accept Path objects --- src/sage/misc/persist.pyx | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/sage/misc/persist.pyx b/src/sage/misc/persist.pyx index a5711ef8d5f..0b275ea38b5 100644 --- a/src/sage/misc/persist.pyx +++ b/src/sage/misc/persist.pyx @@ -160,6 +160,16 @@ def load(*filename, compress=True, verbose=True, **kwargs): sage: load(t) # needs numpy sage: hello # needs numpy + + Path objects are supported:: + + sage: from pathlib import Path + sage: import tempfile + sage: with tempfile.TemporaryDirectory() as d: + ....: p = Path(d) / "test_path" + ....: save(1, p) + ....: load(p) + 1 """ import sage.repl.load if len(filename) != 1: @@ -172,6 +182,9 @@ def load(*filename, compress=True, verbose=True, **kwargs): return filename = filename[0] + # ensure that filename is a string + if not isinstance(filename, str): + filename = os.fspath(filename) if sage.repl.load.is_loadable_filename(filename): sage.repl.load.load(filename, globals()) @@ -213,7 +226,9 @@ def _base_save(obj, filename, compress=True): Otherwise this is equivalent to :func:`_base_dumps` just with the resulting pickle data saved to a ``.sobj`` file. """ - + # ensure that filename is a string + if not isinstance(filename, str): + filename = os.fspath(filename) filename = _normalize_filename(filename) with open(filename, 'wb') as fobj: @@ -278,7 +293,20 @@ def save(obj, filename, compress=True, **kwargs): ....: save((1,1), f.name) ....: load(f.name) (1, 1) + + Check that Path objects work:: + + sage: from pathlib import Path + sage: import tempfile + sage: with tempfile.TemporaryDirectory() as d: + ....: p = Path(d) / "test_path" + ....: save(1, p) + ....: load(p) + 1 """ + # ensure that filename is a string + if not isinstance(filename, str): + filename = os.fspath(filename) if not os.path.splitext(filename)[1] or not hasattr(obj, 'save'): filename = _normalize_filename(filename)