Skip to content

Commit 180fd50

Browse files
authored
load save with pathlib.Path objects
For python >= 3.6, objects representing paths now have the option to have a dunder `__fspath__` (See PEP 519 for more info) to return the string (or bytes) representation of the path. Pathlib on 3.6 includes this method so we should check for it first. Then, for pathlib objects from the py 3.4-3.5x, `__fspath__` is not available, so we dip into the py3k module to get the current python version's (2 or 3) string method (`unicode` in this case). So overall we're allowing filename to be a path object, but ensuring that it will be converted to the string/bytes representation of the path before passing it on to `image_klass.from_filename` My only reservations is that `nib.load` lowest entry point for this type of handling, because if some one really wants to call `from_filename` from an image_klass directly, they won't have this pathlib compatibility- however I think that `nib.load` is a very common entry point, which justifies the placement.
1 parent 1140e18 commit 180fd50

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

nibabel/loadsave.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .filebasedimages import ImageFileError
1818
from .imageclasses import all_image_classes
1919
from .arrayproxy import is_proxy
20-
from .py3k import FileNotFoundError
20+
from .py3k import FileNotFoundError, unicode
2121
from .deprecated import deprecate_with_version
2222

2323

@@ -36,6 +36,11 @@ def load(filename, **kwargs):
3636
img : ``SpatialImage``
3737
Image of guessed type
3838
'''
39+
if hasattr(filename, '__fspath__'):
40+
filename = filename.__fspath__()
41+
else:
42+
filename = unicode(filename)
43+
3944
if not op.exists(filename):
4045
raise FileNotFoundError("No such file: '%s'" % filename)
4146
sniff = None

0 commit comments

Comments
 (0)