Welcome, guest | Sign In | My Account | Store | Cart

This is a fork of recipe #577024 which describes an enum type for Python using __slots__ and read-only variables. Apart from the enum with default positional argument values, this one adds another enum type using keyword arguments.

Python, 25 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Enum type with default positional values
# Enum('STATE', 'A','B','C') => returns object
# e so that e.A=>0, e.B=>1, e.C=>2 etc.

def Enum(name, *args):
    args_m = [arg for arg in args if type(arg)==str]
    return type(name, (object,), dict(((v,k) for k, v in enumerate(args_m)), __slots__=args_m))() 

# Enum type with keyword values
# Enum('STATE',A=1, B=3,C=2) => returns object 
# e so that e.A=1, e.B=>3, e.C=>2 etc.

Enum_kw = lambda name, **kwargs: type(name, (object,), [item for item in (kwargs.update({'__slots__': [k for k in kwargs]}), kwargs)][1])()

e=Enum('STATE','A','B','C','D')
print e.A, e.B, e.C
#e.A=1    # Can't do this
#e.X=100   # Can't do this 

e=Enum_kw('STATE',A=1,B=2,C=3)
print e.A, e.B, e.C
# Can't change existing attribute
# e.A=10
# Can't assign new attributes
# e.X=100

This is a concise rewrite of the Enum type in recipe #577024 and also adds a keyword enum type. The main difference is that this uses positional and keyword arguments and supplies a secondary enum type. __slots__ is used here also and the enum values remain read-only.

Created by Anand on Mon, 22 Feb 2010 (MIT)
Python recipes (4591)
Anand's recipes (38)

Required Modules

  • (none specified)

Other Information and Tasks