You are on page 1of 7

© 2019 MathByte Academy

The pickle Module

Python specific

A way to represent an object in a persistent way à disk, transmission

Create an object’s representation à serializing


marshalling
Reload object from representation à deserializing

obj serialize deserialize obj


101100011001…

Pickle is a binary serialization (by default)

Focus on dictionaries à Can be used for other object types

© 2019 MathByte Academy


Danger Zone!

Unpickling (deserializing) can execute code

à not safe!

Only unpickle data you trust

© 2019 MathByte Academy


Usage

import pickle

dump à pickle to file


load à unpickle from file

dumps à returns a (string) pickled representation à store in a variable


loads à unpickle from supplied argument

© 2019 MathByte Academy


Equality and Identity

equality à == identity à is

0011
pickle 0000 unpickle
dict1 dict2
1111
01
id=100 id=200

dict1 == dict2 à True à Custom objects will need to implement __eq__

dict1 is dict2 à False

© 2019 MathByte Academy


Equality and Identity

While pickling, Python will not re-serialize an object it has already serialized

à recursive objects can be pickled

à shared objects are deserialized as shared objects as well

obj1 obj1

• prop1 pickle / unpickle • prop1


• prop2 • prop2

© 2019 MathByte Academy


Coding

© 2019 MathByte Academy

You might also like