enum in Python

A

Andrew Chalk

What is the best way to implement an equivalent of C's 'enum' type in
Python?

As a rank Python beginner I've used a dictionary, but presumably there is a
better way.

Thanks
 
D

David M. Cook

As a rank Python beginner I've used a dictionary, but presumably there is a
better way.

I've seen idioms like

FOO, BAR, BAZ = range(3)

used.

Dave Cook
 
S

Scott David Daniels

David said:
I've seen idioms like

FOO, BAR, BAZ = range(3)

used.

Dave Cook

For 2.3 or after:

class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)

To use:
codes = Enumerate('FOO BAR BAZ')
codes.BAZ will be 2 and so on.


if you only have 2.2, precede this with:

from __future__ import generators

def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1




codes.BAZ
 
H

Harry George

Scott David Daniels said:
For 2.3 or after:

class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)

To use:
codes = Enumerate('FOO BAR BAZ')
codes.BAZ will be 2 and so on.


if you only have 2.2, precede this with:

from __future__ import generators

def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1




codes.BAZ

We have some code which uses fancy cookbooked enumerate patterns but
they seem unnecessarily complex to me. Even the pattern above is a
runtime build of what should be a static type definition. Instead, in
any Python version, I use:

class Code:
unknown=0
FOO=1
BAR=2
BAZ=3

mycode=Code.unknown #typical initialization

mycode=Code.FOO #specific value assigned.

You get:
a) type-specific namespace

b) can choose the numbers (e.g., when they are predefined in a data
file format)

c) errors are detected

d) static assignment allows compiler optimizations (don't know if
any are actually done).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top