MCPcopy Index your code
hub / github.com/python/cpython / Enum

Class Enum

Lib/enum.py:1134–1355  ·  view source on GitHub ↗

Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) <C

Source from the content-addressed store, hash-verified

1132
1133
1134class Enum(metaclass=EnumType):
1135 """
1136 Create a collection of name/value pairs.
1137
1138 Example enumeration:
1139
1140 >>> class Color(Enum):
1141 ... RED = 1
1142 ... BLUE = 2
1143 ... GREEN = 3
1144
1145 Access them by:
1146
1147 - attribute access:
1148
1149 >>> Color.RED
1150 <Color.RED: 1>
1151
1152 - value lookup:
1153
1154 >>> Color(1)
1155 <Color.RED: 1>
1156
1157 - name lookup:
1158
1159 >>> Color['RED']
1160 <Color.RED: 1>
1161
1162 Enumerations can be iterated over, and know how many members they have:
1163
1164 >>> len(Color)
1165 3
1166
1167 >>> list(Color)
1168 [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
1169
1170 Methods can be added to enumerations, and members can have their own
1171 attributes -- see the documentation for details.
1172 """
1173
1174 def __new__(cls, value):
1175 # all enum instances are actually created during class construction
1176 # without calling this method; this method is called by the metaclass'
1177 # __call__ (i.e. Color(3) ), and by pickle
1178 if type(value) is cls:
1179 # For lookups like Color(Color.RED)
1180 return value
1181 # by-value search for a matching enum member
1182 # see if it's in the reverse mapping (for hashable values)
1183 try:
1184 return cls._value2member_map_[value]
1185 except KeyError:
1186 # Not found, no need to do long O(n) search
1187 pass
1188 except TypeError:
1189 # not there, now do long search -- O(n) behavior
1190 for name, unhashable_values in cls._unhashable_values_map_.items():
1191 if value in unhashable_values:

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…