Allow torch.load and torch.save to take pathlib.Path (#3589)
* Allow torch.load to take pathlib.Path
pathlib has been python standard library for filesystem path since python 3.4
But `torch.load` currently cannot take `pathlib.Path` as its filename of state dictionary.
I changed `torch.load` and `_with_file_like` to check so that they can accept `pathlib.Path` typed filepath.
* Fix flake8: too long line & indentation
diff --git a/torch/serialization.py b/torch/serialization.py
index 22b87676..4569ea4 100644
--- a/torch/serialization.py
+++ b/torch/serialization.py
@@ -14,6 +14,7 @@
import cPickle as pickle
else:
import pickle
+ import pathlib
DEFAULT_PROTOCOL = 2
@@ -106,7 +107,9 @@
it in 'mode' if it is a string filename.
"""
new_fd = False
- if isinstance(f, str) or (sys.version_info[0] == 2 and isinstance(f, unicode)):
+ if isinstance(f, str) or \
+ (sys.version_info[0] == 2 and isinstance(f, unicode)) or \
+ (sys.version_info[0] == 3 and isinstance(f, pathlib.Path)):
new_fd = True
f = open(f, mode)
try:
@@ -249,7 +252,9 @@
"""
new_fd = False
- if isinstance(f, str) or (sys.version_info[0] == 2 and isinstance(f, unicode)):
+ if isinstance(f, str) or \
+ (sys.version_info[0] == 2 and isinstance(f, unicode)) or \
+ (sys.version_info[0] == 3 and isinstance(f, pathlib.Path)):
new_fd = True
f = open(f, 'rb')
try: