In the previous lesson, I took a first stab at the code adding the
Grid class with the
evolve method to create the next frame. In this lesson, I’ll dive into a better way to store initial patterns instead of hard coding patterns in our Python, it’d be good to store them in a file.
00:17 That way a user could pass in their own file and see any pattern they wish. I’ve chosen to use the TOML file format as it’s relatively easy for a human to read and the data types in it map nicely to our pattern.
00:43 Your code can correctly use whichever library is there. TOML files get represented in Python as dictionaries, so a TOML section denoted by square brackets will be a key to a dictionary and used as our pattern ID.
I’m back inside the
patterns.py file where the
Pattern data class is defined. This time though, I’ve added some stuff starting out as promised, with a
except block that attempts to import the standard library’s
If the user is in Python 3.11 or greater, the module gets loaded. If not, the exception fires and
tomli is loaded. Instead, notice that I’m aliasing the
tomli library so that I can always use
tomllib everywhere in the code.
02:09 A factory method is what you call a method that returns an instance of the class it is associated with. Note, this is a class method. It gets called on the class itself and returns an instance object.
02:57 This code could be a bit friendlier. Calling it with a name that doesn’t exist will cause a key error. A better programmer would wrap this with some error handling code and print out a helpful message.
03:26 This is the TOML file I plan to ship with the module. It has a bunch of different named sections, one for each pattern, and inside each section, the list of alive cell coordinates. Time to test our pattern loading code. Off to the REPL.
Become a Member to join the conversation.