(cls, value)
| 1144 | """ |
| 1145 | |
| 1146 | def __new__(cls, value): |
| 1147 | # all enum instances are actually created during class construction |
| 1148 | # without calling this method; this method is called by the metaclass' |
| 1149 | # __call__ (i.e. Color(3) ), and by pickle |
| 1150 | if type(value) is cls: |
| 1151 | # For lookups like Color(Color.RED) |
| 1152 | return value |
| 1153 | # by-value search for a matching enum member |
| 1154 | # see if it's in the reverse mapping (for hashable values) |
| 1155 | try: |
| 1156 | return cls._value2member_map_[value] |
| 1157 | except KeyError: |
| 1158 | # Not found, no need to do long O(n) search |
| 1159 | pass |
| 1160 | except TypeError: |
| 1161 | # not there, now do long search -- O(n) behavior |
| 1162 | for name, unhashable_values in cls._unhashable_values_map_.items(): |
| 1163 | if value in unhashable_values: |
| 1164 | return cls[name] |
| 1165 | for name, member in cls._member_map_.items(): |
| 1166 | if value == member._value_: |
| 1167 | return cls[name] |
| 1168 | # still not found -- verify that members exist, in-case somebody got here mistakenly |
| 1169 | # (such as via super when trying to override __new__) |
| 1170 | if not cls._member_map_: |
| 1171 | if getattr(cls, '_%s__in_progress' % cls.__name__, False): |
| 1172 | raise TypeError('do not use `super().__new__; call the appropriate __new__ directly') from None |
| 1173 | raise TypeError("%r has no members defined" % cls) |
| 1174 | # |
| 1175 | # still not found -- try _missing_ hook |
| 1176 | try: |
| 1177 | exc = None |
| 1178 | result = cls._missing_(value) |
| 1179 | except Exception as e: |
| 1180 | exc = e |
| 1181 | result = None |
| 1182 | try: |
| 1183 | if isinstance(result, cls): |
| 1184 | return result |
| 1185 | elif ( |
| 1186 | Flag is not None and issubclass(cls, Flag) |
| 1187 | and cls._boundary_ is EJECT and isinstance(result, int) |
| 1188 | ): |
| 1189 | return result |
| 1190 | else: |
| 1191 | ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__)) |
| 1192 | if result is None and exc is None: |
| 1193 | raise ve_exc |
| 1194 | elif exc is None: |
| 1195 | exc = TypeError( |
| 1196 | 'error in %s._missing_: returned %r instead of None or a valid member' |
| 1197 | % (cls.__name__, result) |
| 1198 | ) |
| 1199 | if not isinstance(exc, ValueError): |
| 1200 | exc.__context__ = ve_exc |
| 1201 | raise exc |
| 1202 | finally: |
| 1203 | # ensure all variables that could hold an exception are destroyed |
no test coverage detected