Pickle turns an object into bytes you can save in a file and read back later. The object keeps its type and all of its values, so you get back the same thing you put in.
SQL is the language you use to ask a database questions. If you want to get better at it, SQLCrab runs real queries in the browser, nothing to install.
That is more than JSON can do, which only knows about lists, dictionaries, strings and numbers.
The pickle module can be used for object serialization.
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)
When to use it
pickle.dumps(obj)gives you the bytes, useful for sending over a socket.pickle.loads(data)turns bytes back into an object.pickle.dump(obj, file)writes straight to an open file.pickle.load(file)reads it back.- Protocol 5 is the default in Python 3.8 and up and is faster.
Never unpickle a file you did not create yourself. A pickle file can run code when it is loaded, so only open files from a source you trust.
Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.
