Skip to content

Commit 22cf736

Browse files
author
Release Manager
committed
sagemathgh-41037: Enable save/load to accept Path objects - [x] The title is concise and informative. - [x] I have created tests covering the changes. URL: sagemath#41037 Reported by: Edgar Costa Reviewer(s): Edgar Costa, Frédéric Chapoton, Michael Orlitzky, user202729
2 parents 014cd9a + 8885ac3 commit 22cf736

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/sage/misc/persist.pyx

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,16 @@ def load(*filename, compress=True, verbose=True, **kwargs):
160160
sage: load(t) # needs numpy
161161
sage: hello # needs numpy
162162
<fortran ...>
163+
164+
Path objects are supported::
165+
166+
sage: from pathlib import Path
167+
sage: import tempfile
168+
sage: with tempfile.TemporaryDirectory() as d:
169+
....: p = Path(d) / "test_path"
170+
....: save(1, p)
171+
....: load(p)
172+
1
163173
"""
164174
import sage.repl.load
165175
if len(filename) != 1:
@@ -172,6 +182,9 @@ def load(*filename, compress=True, verbose=True, **kwargs):
172182
return
173183

174184
filename = filename[0]
185+
# ensure that filename is a string
186+
if not isinstance(filename, str):
187+
filename = os.fspath(filename)
175188

176189
if sage.repl.load.is_loadable_filename(filename):
177190
sage.repl.load.load(filename, globals())
@@ -213,7 +226,9 @@ def _base_save(obj, filename, compress=True):
213226
Otherwise this is equivalent to :func:`_base_dumps` just with the resulting
214227
pickle data saved to a ``.sobj`` file.
215228
"""
216-
229+
# ensure that filename is a string
230+
if not isinstance(filename, str):
231+
filename = os.fspath(filename)
217232
filename = _normalize_filename(filename)
218233

219234
with open(filename, 'wb') as fobj:
@@ -278,7 +293,20 @@ def save(obj, filename, compress=True, **kwargs):
278293
....: save((1,1), f.name)
279294
....: load(f.name)
280295
(1, 1)
296+
297+
Check that Path objects work::
298+
299+
sage: from pathlib import Path
300+
sage: import tempfile
301+
sage: with tempfile.TemporaryDirectory() as d:
302+
....: p = Path(d) / "test_path"
303+
....: save(1, p)
304+
....: load(p)
305+
1
281306
"""
307+
# ensure that filename is a string
308+
if not isinstance(filename, str):
309+
filename = os.fspath(filename)
282310

283311
if not os.path.splitext(filename)[1] or not hasattr(obj, 'save'):
284312
filename = _normalize_filename(filename)

0 commit comments

Comments
 (0)