Skip to content

Commit 5ea6129

Browse files
committed
fixes #128
1 parent b5dc0ad commit 5ea6129

File tree

3 files changed

+48
-32
lines changed

3 files changed

+48
-32
lines changed

fastcore/_nbdev.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@
116116
"Path.readlines": "02_utils.ipynb",
117117
"Path.mk_write": "02_utils.ipynb",
118118
"Path.ls": "02_utils.ipynb",
119+
"open_file": "02_utils.ipynb",
119120
"save_pickle": "02_utils.ipynb",
120121
"load_pickle": "02_utils.ipynb",
121122
"Path.__repr__": "02_utils.ipynb",

fastcore/utils.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
'Float', 'tuplify', 'detuplify', 'replicate', 'uniqueify', 'setify', 'merge', 'is_listy', 'range_of',
88
'groupby', 'last_index', 'shufflish', 'IterLen', 'ReindexCollection', 'num_methods', 'rnum_methods',
99
'inum_methods', 'fastuple', 'trace', 'compose', 'maps', 'partialler', 'mapped', 'instantiate', 'using_attr',
10-
'Self', 'Self', 'save_pickle', 'load_pickle', 'bunzip', 'join_path_file', 'urlread', 'urljson', 'run',
11-
'do_request', 'sort_by_run', 'PrettyString', 'round_multiple', 'even_mults', 'num_cpus', 'add_props',
10+
'Self', 'Self', 'open_file', 'save_pickle', 'load_pickle', 'bunzip', 'join_path_file', 'urlread', 'urljson',
11+
'run', 'do_request', 'sort_by_run', 'PrettyString', 'round_multiple', 'even_mults', 'num_cpus', 'add_props',
1212
'ContextManagers', 'typed', 'set_num_threads', 'ProcessPoolExecutor', 'ThreadPoolExecutor', 'parallel',
1313
'run_procs', 'parallel_gen', 'threaded']
1414

@@ -17,7 +17,7 @@
1717
from .foundation import *
1818
from functools import wraps
1919

20-
import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex
20+
import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex,bz2,gzip
2121
from contextlib import contextmanager
2222
from pdb import set_trace
2323
from urllib.request import Request,urlopen
@@ -528,21 +528,24 @@ def ls(self:Path, n_max=None, file_type=None, file_exts=None):
528528
if n_max is not None: res = itertools.islice(res, n_max)
529529
return L(res)
530530

531+
# Cell
532+
def open_file(fn, mode='r'):
533+
"Open a file, with optional compression if gz or bz2 suffix"
534+
if isinstance(fn, io.IOBase): return fn
535+
fn = Path(fn)
536+
if fn.suffix=='.bz2': return bz2.BZ2File(fn, mode)
537+
elif fn.suffix=='.gz' : return gzip.GzipFile(fn, mode)
538+
else: return open(fn,mode)
539+
531540
# Cell
532541
def save_pickle(fn, o):
533542
"Save a pickle file, to a file name or opened file"
534-
fn = Path(fn)
535-
if not isinstance(fn, io.IOBase): fn = open(fn,'wb')
536-
try: pickle.dump(o, fn)
537-
finally: fn.close()
543+
with open_file(fn, 'wb') as f: pickle.dump(o, f)
538544

539545
# Cell
540546
def load_pickle(fn):
541547
"Load a pickle file from a file name or opened file"
542-
fn = Path(fn)
543-
if not isinstance(fn, io.IOBase): fn = open(fn,'rb')
544-
try: return pickle.load(fn)
545-
finally: fn.close()
548+
with open_file(fn, 'rb') as f: return pickle.load(f)
546549

547550
# Cell
548551
@patch

nbs/02_utils.ipynb

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"from fastcore.foundation import *\n",
2121
"from functools import wraps\n",
2222
"\n",
23-
"import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex\n",
23+
"import mimetypes,bz2,pickle,random,json,urllib,subprocess,shlex,bz2,gzip\n",
2424
"from contextlib import contextmanager\n",
2525
"from pdb import set_trace\n",
2626
"from urllib.request import Request,urlopen\n",
@@ -2981,19 +2981,33 @@
29812981
"txt_files[0],ipy_files[0]"
29822982
]
29832983
},
2984+
{
2985+
"cell_type": "code",
2986+
"execution_count": null,
2987+
"metadata": {},
2988+
"outputs": [],
2989+
"source": [
2990+
"#hide\n",
2991+
"path = Path()\n",
2992+
"pkl = pickle.dumps(path)\n",
2993+
"p2 = pickle.loads(pkl)\n",
2994+
"test_eq(path.ls()[0], p2.ls()[0])"
2995+
]
2996+
},
29842997
{
29852998
"cell_type": "code",
29862999
"execution_count": null,
29873000
"metadata": {},
29883001
"outputs": [],
29893002
"source": [
29903003
"#export\n",
2991-
"def save_pickle(fn, o):\n",
2992-
" \"Save a pickle file, to a file name or opened file\"\n",
3004+
"def open_file(fn, mode='r'):\n",
3005+
" \"Open a file, with optional compression if gz or bz2 suffix\"\n",
3006+
" if isinstance(fn, io.IOBase): return fn\n",
29933007
" fn = Path(fn)\n",
2994-
" if not isinstance(fn, io.IOBase): fn = open(fn,'wb')\n",
2995-
" try: pickle.dump(o, fn)\n",
2996-
" finally: fn.close()"
3008+
" if fn.suffix=='.bz2': return bz2.BZ2File(fn, mode)\n",
3009+
" elif fn.suffix=='.gz' : return gzip.GzipFile(fn, mode)\n",
3010+
" else: return open(fn,mode)"
29973011
]
29983012
},
29993013
{
@@ -3003,12 +3017,9 @@
30033017
"outputs": [],
30043018
"source": [
30053019
"#export\n",
3006-
"def load_pickle(fn):\n",
3007-
" \"Load a pickle file from a file name or opened file\"\n",
3008-
" fn = Path(fn)\n",
3009-
" if not isinstance(fn, io.IOBase): fn = open(fn,'rb')\n",
3010-
" try: return pickle.load(fn)\n",
3011-
" finally: fn.close()"
3020+
"def save_pickle(fn, o):\n",
3021+
" \"Save a pickle file, to a file name or opened file\"\n",
3022+
" with open_file(fn, 'wb') as f: pickle.dump(o, f)"
30123023
]
30133024
},
30143025
{
@@ -3017,11 +3028,10 @@
30173028
"metadata": {},
30183029
"outputs": [],
30193030
"source": [
3020-
"with tempfile.NamedTemporaryFile() as f:\n",
3021-
" fn = Path(f.name)\n",
3022-
" save_pickle(fn, 't')\n",
3023-
" t = load_pickle(fn)\n",
3024-
"test_eq(t,'t')"
3031+
"#export\n",
3032+
"def load_pickle(fn):\n",
3033+
" \"Load a pickle file from a file name or opened file\"\n",
3034+
" with open_file(fn, 'rb') as f: return pickle.load(f)"
30253035
]
30263036
},
30273037
{
@@ -3030,10 +3040,12 @@
30303040
"metadata": {},
30313041
"outputs": [],
30323042
"source": [
3033-
"#hide\n",
3034-
"pkl = pickle.dumps(path)\n",
3035-
"p2 = pickle.loads(pkl)\n",
3036-
"test_eq(path.ls()[0], p2.ls()[0])"
3043+
"for suf in '.pkl','.bz2','.gz':\n",
3044+
" with tempfile.NamedTemporaryFile(suffix=suf) as f:\n",
3045+
" fn = Path(f.name)\n",
3046+
" save_pickle(fn, 't')\n",
3047+
" t = load_pickle(fn)\n",
3048+
" test_eq(t,'t')"
30373049
]
30383050
},
30393051
{

0 commit comments

Comments
 (0)