Stats

66 Contributors: 6 Saturday, September 17, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Pickle data serialisation

Syntax

  • pickle.dump(object,file,protocol) #To serialize an object

  • pickle.load(file) #To de-serialize an object

  • pickle.dumps(object, protocol) # To serialize an object to bytes

  • pickle.loads(buffer) # To de-serialzie an object from bytes

Parameters

ParameterDetails
objectThe object which is to be stored
fileThe open file which will contain the object
protocolThe protocol used for pickling the object (optional parameter)
bufferA bytes object that contains a serialized object

Remarks

Pickleable types

The following objects are picklable.

  • None, True, and False
  • numbers (of all types)
  • strings (of all types)
  • tuples, lists, sets, and dicts containing only picklable objects
  • functions defined at the top level of a module
  • built-in functions
  • classes that are defined at the top level of a module
    • instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see the official docs for details).

Based on the official Python documentation.

pickle and security

The pickle module is not secure. It should not be used when receiving the serialized data from an untrusted party, such as over the Internet.

Related Examples