| 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: |
| 1192 | return cls[name] |
| 1193 | for name, member in cls._member_map_.items(): |
| 1194 | if value == member._value_: |
| 1195 | return cls[name] |
| 1196 | # still not found -- verify that members exist, in-case somebody got here mistakenly |
| 1197 | # (such as via super when trying to override __new__) |
| 1198 | if not cls._member_map_: |
| 1199 | if getattr(cls, '_%s__in_progress' % cls.__name__, False): |
| 1200 | raise TypeError('do not use `super().__new__; call the appropriate __new__ directly') from None |
| 1201 | raise TypeError("%r has no members defined" % cls) |
| 1202 | # |
| 1203 | # still not found -- try _missing_ hook |
| 1204 | try: |
| 1205 | exc = None |
| 1206 | result = cls._missing_(value) |
| 1207 | except Exception as e: |
| 1208 | exc = e |
| 1209 | result = None |
| 1210 | try: |
| 1211 | if isinstance(result, cls): |
| 1212 | return result |
| 1213 | elif ( |
| 1214 | Flag is not None and issubclass(cls, Flag) |
| 1215 | and cls._boundary_ is EJECT and isinstance(result, int) |
| 1216 | ): |
| 1217 | return result |
| 1218 | else: |
| 1219 | ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__)) |
| 1220 | if result is None and exc is None: |
| 1221 | raise ve_exc |
| 1222 | elif exc is None: |
| 1223 | exc = TypeError( |
| 1224 | 'error in %s._missing_: returned %r instead of None or a valid member' |
| 1225 | % (cls.__name__, result) |
| 1226 | ) |
| 1227 | if not isinstance(exc, ValueError): |
| 1228 | exc.__context__ = ve_exc |
| 1229 | raise exc |
| 1230 | finally: |
| 1231 | # ensure all variables that could hold an exception are destroyed |