Skip to content

Commit 66ebac2

Browse files
committed
make a backup of the data file before saving
Right now, if a program crashes in the middle of saving, you lose all your data. This ensures that the old file is first moved, then the new file is saved, and only then the old file is removed.
1 parent d79512f commit 66ebac2

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

adaptive/learner/base_learner.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
import abc
4+
import os
45
from contextlib import suppress
56
from copy import deepcopy
67

@@ -174,8 +175,16 @@ def save(self, fname, compress=True):
174175
using compression, one must load it with compression too.
175176
"""
176177
data = self._get_data()
178+
179+
backup = os.path.join(".", fname)
180+
if os.path.exists(fname):
181+
os.rename(fname, backup)
182+
177183
save(fname, data, compress)
178184

185+
if os.path.exists(backup):
186+
os.remove(backup)
187+
179188
def load(self, fname, compress=True):
180189
"""Load the data of a learner from a pickle file.
181190
@@ -187,9 +196,14 @@ def load(self, fname, compress=True):
187196
If the data is compressed when saved, one must load it
188197
with compression too.
189198
"""
190-
with suppress(FileNotFoundError, EOFError):
199+
try:
191200
data = load(fname, compress)
192201
self._set_data(data)
202+
except (FileNotFoundError, EOFError):
203+
with suppress(FileNotFoundError):
204+
backup = os.path.join(".", fname)
205+
data = load(backup, compress)
206+
self._set_data(data)
193207

194208
def __getstate__(self):
195209
return deepcopy(self.__dict__)

0 commit comments

Comments
 (0)