enum question

Terry Hancock hancock at anansispaceworks.com
Wed Mar 9 16:48:47 EST 2005


On Friday 04 March 2005 02:54 pm, M.N.A.Smadi wrote:
> does python support a C-like enum statement where one can define a 
> variable with prespesified range of values?

No, but in most situations where I would've used an enum, I use a 
trivial class like this:

class states:
    ON, OFF, UNKNOWN, UNDEFINED, INCOMPREHENSIBLE, SILLY = range(6)

The values are actually integers of course.  Then I can pass named values to a function:

from silly import walk, states

walk(kind=states.SILLY)

If you want to make them more like a bitfield, you could always do this instead:

class properties:
    AUDIBLE, VISIBLE, SPEAKABLE = [2**i for i in range(3)]

then you can have, e.g.:

evil(allowed=False, AUDIBLE|VISIBLE|SPEAKABLE)

if mode & AUDIBLE: hear()
if mode & VISIBLE: see()

etc.

Obviously if you want more rigid assurance of the behavior of the variable
in question you'd need more work. But most of the time, enums are just to
make the code more readable, so I do this, which is extremely compact,
and yet pretty clear.  You *can* drop the enum values into the module
namespace, but then importing them is a pain, so I like to qualify them
with the class as shown.

Cheers,
Terry


-- 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list