Skip to content

Commit b2b6663

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

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
@@ -159,6 +159,16 @@ def load(*filename, compress=True, verbose=True, **kwargs):
159159
sage: load(t) # needs numpy
160160
sage: hello # needs numpy
161161
<fortran ...>
162+
163+
Path objects are supported::
164+
165+
sage: from pathlib import Path
166+
sage: import tempfile
167+
sage: with tempfile.TemporaryDirectory() as d:
168+
....: p = Path(d) / "test_path"
169+
....: save(1, p)
170+
....: load(p)
171+
1
162172
"""
163173
import sage.repl.load
164174
if len(filename) != 1:
@@ -171,6 +181,9 @@ def load(*filename, compress=True, verbose=True, **kwargs):
171181
return
172182

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

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

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

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

0 commit comments

Comments
 (0)