My groups’ project this semester is A-Life-Challenge-2.0, an artificial life simulation. Our simulation involves “organisms” moving around on a canvas, consuming and reproducing. These organisms have different “traits” like energy source, sleep, movement; where there are various options within that trait. For example the possible energy sources are photosynthesis, herbivore, carnivore, and omnivore. Naturally, we initially represented the trait options in code as lists:
energy_source_options = [‘photosynthesis’, ‘herbivore’, ‘carnivore’, ‘omnivore’]
sleep_options = [‘diurnal’, ‘nocturnal’]
movement_options = [‘stationary’, ‘bipedal’, ‘quadripedal’]
While this representation works, encoding the information as raw strings has some drawbacks. One drawback is that it cannot detect mistyping errors. For example if you type if phenotype == ‘stationery’
when you meant if phenotype == ‘stationary’
, then this could lead to a hard-to-detect bug. Instead of using lists, Jakob suggested using the Python enum
package which provides a way to create enumerations, data types that have some useful properties than relying on a list of strings. With enums, you can bind names to unique values, and you can still iterate over the members. There are two ways you can represent enums. The first is a “class-style”:
class Sleep(Enum):
DIURNAL = 1
NOCTURNAL = 2
The other option is a “functional-style:
Sleep = Enum('Sleep': ['DIURNAL', 'NOCTURNAL'])
In either way, you then refer to enum members with syntax like Sleep.DIURNAL.
This has some advantages over the previous way. First, is that in prevents typos since a mis-spelling will lead to a syntax error. Second, it is arguably more readable since it’s obvious that diurnal is a “member” of sleep
One issue we ran into though is pickling objects that have enums that were created using the “functional-style”. I wasn’t able to pinpoint why this was an issue (I doubt it was a bug in the pickle
or enum
packages as much as I would like to think so), but switching over everything the “class-style” fixed it.
There are many more uses to enums that what I’ve listed here, but I’m happy to have learned about this new tech and use it to organize our project.
Leave a Reply