c enum - how to do this in python?

Edward K. Ream edream at tds.net
Sat Feb 22 09:27:47 EST 2003


> C has enum to define named constant like:
> enum { M0, M1, M2, MCOUNT };
> (MCOUNT gives the number of constants, nice for loops or so)
>
> How to do this in Python?

In many cases it is enough simply to use strings instead of ints.  No
"declaration" is required at all.  You can use strings as dictionary keys,
and unless speed is a big consideration, a test such as if kind ==
"thisKind" is as clear as can be.

Coming from a C background I started off using constructs such as:

M0, M1, M2, MCOUNT = range(4)

but after a while I just got lazy :-)  Theoretically one loses some error
checking by not using "real" enums, but in practice this doesn't seem to be
too big a deal.  I've never had any harm come from it: misspelled constants
get caught quickly enough.  I'm not saying you _should_ use strings instead
of enums, only that you _can_ do so if you are as lazy as I am.

BTW, this pattern works well with dispatcher dictionaries (recipe 1.6 in the
Python Cookbook).

Edward
--------------------------------------------------------------------
Edward K. Ream   email:  edream at tds.net
Leo: Literate Editor with Outlines
Leo: http://personalpages.tds.net/~edream/front.html
--------------------------------------------------------------------






More information about the Python-list mailing list