Python Enums

Python Enums

PEP-435, Python Enum, has been approved and will be implemented (apparently) in Python 3.4: this is quite a change and, at least in my opinion, a long overdue language feature.

In future, one can avoid doing something ugly like this:

(months.py)
JANUARY = 1
FEBRUARY = 2
...
DECEMBER = 12

then, in another module:

import months
...
if month == months.JANUARY:
    print 'What is three times January?'
    return 3 * month

This would work today and make, obviously, perfect sense, right?
With Enum instea, this would be written:

from enum import Enum

class Month(Enum):
    january = 1
    ...
    december = 12

month = Month.january
print month     # prints 'Month.january'
print 3 * month # raises an exception

Go check out the PEP!

Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: