Using Python Safe Pickle

Background

I have inherited a code base with many suggestions try ... except:. Most of them are too wide, and to make it painful to debug. I went through and changed each to the most reasonable form, which usually involves the removal or indication of exception (s).

Problem

But I'm a little puzzled by this:

try:
    with open(self.session_filename, "rb") as f:
        data = cPickle.loads(zlib.decompress(f.read()))
except:
    # we didn't need your file anyway!
    return

I want to handle exceptions specifically, but Python docs on Pickle say:

pickle.UnpicklingError exception

This exception occurs when a problem occurs with the object. Note that other exceptions may also be unickling, including (but not necessarily limited to) AttributeError , EOFError, ImportErrorand IndexError.

Translation: a method can throw something!

, , , .

, :

  • - .
  • , , .
  • . , , .

, .

+4
2

, , , .

try:
    with open(self.session_filename, "rb") as f:
         data = cPickle.loads(zlib.decompress(f.read()))
except pickle.UnpicklingError as e:
    # normal, somewhat expected
    continue
except (AttributeError,  EOFError, ImportError, IndexError) as e:
    # secondary errors
    print(traceback.format_exc(e))
    continue
except Exception as e:
    # everything else, possibly fatal
    print(traceback.format_exc(e))
    return
+3

, , : , cPickle.loads .

, , try ... except. :

with open(self.session_filename, "rb") as f:
    uncompressed_data = zlib.decompress(f.read())

try:
    data = cPickle.loads(uncompressed_data)
except cPickle.UnpicklingError:
    raise
except Exception as e:
    # Unpickling failed
    raise cPickle.UnpicklingError(repr(e))
0

Source: https://habr.com/ru/post/1612945/


All Articles