An enum for Python

The internet abounds with implementations of enumerations for Python, but I thought it might be fun to take a crack at making one. My goals were:

  1. Immutability: users shouldn’t be able to modify the value at runtime
  2. Simplicity of definition: They should be easy to define
  3. Uniqueness: Two enum values aren’t equal unless they are the same, no matter what their numeric value is
  4. Iteration: The user can iterate over the values in the enum
  5. Pickle-able: Naturally…

Here’s what I came up with.

It uses a metaclass to add a custom __setattr__, __getattr__, and __iter__ to the user’s “enum class”, and it looks like this:

import enum

class Level(metaclass=enum.Enum):
  LOW=1
  MEDIUM=2
  HIGH=3
  
x = Level.LOW
Level.HIGH = 19 # Throws an AttributeError
etc...
Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: