Objects can be serialized: stored in a format for later use. Once an object is serialized, it can be stored in a file and loaded from a file.

The pickle module can be used for object serialization.

Related course: Python Programming Courses & Exercises

Create and dump an object

We start by creating a class and object. Then we use the module dumps() with as parameter the object. We can simply print the serialized output, because why not?

import pickle

class A:
def __init__(self):
self.name = 'A'
self.type = 'class'

obj = A()
dump = pickle.dumps(obj)
print(dump)

Store and load object from file

More practical is to store the serialized object in file. Then we can reload it from that file at any time. To store a serialized object into a file:

import pickle

class A:
def __init__(self):
self.name = 'A'
self.type = 'class'

obj = A()
print(obj.name)
print(obj.type)

bin_file = open('dump.bin',mode='wb')
dump = pickle.dump(obj, bin_file)
bin_file.close()

Then the object can be loaded from the file. This can be done at any time or even from another program.

import pickle

class A:
def __init__(self):
self.name = 'A'
self.type = 'class'

with open('dump.bin') as f:
obj = pickle.load(f)
print(obj.name)
print(obj.type)

Download exercises