Deserialize the Maze
00:00
Deserialize the Maze. To deserialize a binary file into an instance of your Maze
class, you are going to follow the same steps, but in the reverse order.
00:11
Modify your serializer
module by adding new functions to complement the ones you created earlier on. The first function will take a file path as an argument and return the loaded maze object.
00:31 You open the file for reading in binary mode, obtain the file header, and then check the file’s format version before attempting to read its body. If the file format is unsupported, you raise an exception.
00:51 Otherwise, you pass the header and body to another function, which can create a new maze object based on the information provided. In the future, you could branch this code to read the file body differently depending on the detected version. The deserializing function is the next thing to code.
01:22
First, you create an empty list, which you then populate with Square
instances by looping over the square values in the file body. To keep track of the current square index, you enumerate the values and calculate their row and column based on metadata in the header.
01:44
Each bit field is decompressed into the relevant Border
and Role
, which the square’s class constructor requires. A Square
instance is then appended to the squares
list, and the loop repeats.
02:02
Finally, you pass the squares as a tuple to the Maze
constructor. The decompression of a single square value follows the principles outlined earlier in the course when you were choosing how to pack your data into a single byte.
02:54 The bitmask and bit shifting allow you to separate the two pieces of data from a single number. Your enumerations can be seeded with these two numbers, while their resulting members can be wrapped in a tuple and returned.
03:11 Finally, you can verify whether you’ll get the same object that you started with by dumping the test maze into a file and then loading it back.
03:49
You can rely on the equality test provided by your data class, which correctly compares Maze
instances by their value rather than by identity.
03:59 While the original maze and the loaded counterpart are two distinct objects in computer memory, they compare as equal because they’re made up of the same squares.
04:09
There’s one last detail to improve in your current implementation of the maze serialization. Notice that in order to load or dump the maze to a file, you need to import both the Maze
model and the relevant function from the serializer
module.
04:24 That’s not ideal from an object-oriented perspective, so in the next part of the course, you’ll work to change that.
Become a Member to join the conversation.