From f0a8f7572b69affbb5c74120152b4115f60fb9e3 Mon Sep 17 00:00:00 2001 From: Jon Ruttan Date: Sun, 29 Nov 2026 12:54:42 -0500 Subject: [PATCH] feat: an enum module stdlib/enum.py gives Enum, IntEnum, StrEnum, Flag and IntFlag over an EnumType metaclass, with auto(), member(), nonmember(), unique(), the FlagBoundary values and the functional form. D16-enum checks it against CPython 3.14's output. Two gaps follow from x-python running a class body before its names reach the prepared namespace: a name the body reads is still its auto() object, and a name bound twice keeps its last value instead of being refused. __members__ is a dict copy. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + stdlib/enum.py | 923 +++++++++++++++++++++++++++++++++++ tests/specs/D16-enum.spec.md | 116 +++++ 3 files changed, 1040 insertions(+) create mode 100644 stdlib/enum.py create mode 100644 tests/specs/D16-enum.spec.md diff --git a/README.md b/README.md index 33fbe66..d1fb453 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,7 @@ rarely touch the same lines. | `cmath` | x | `lib/python/cmath.x` | | `collections` | x | `lib/python/collections.x` | | `copy` | Python | `stdlib/copy.py` | +| `enum` | Python | `stdlib/enum.py` | | `errno` | x | `lib/python/runtime-flow.x` | | `functools` | Python | `stdlib/functools.py` | | `gc` | x | `lib/python/runtime-flow.x` | diff --git a/stdlib/enum.py b/stdlib/enum.py new file mode 100644 index 0000000..8ef12fa --- /dev/null +++ b/stdlib/enum.py @@ -0,0 +1,923 @@ +"""enum -- sets of named constants. + +x-python's own, written to CPython 3.14's interface. A class over Enum +names its members in its body; each becomes an instance of the class, +made once, and the class is the way to reach them: by attribute, by +value with Color(1), by name with Color['RED'], or by iterating over it. + +Here are Enum and ReprEnum, IntEnum and StrEnum, which mix in int and +str, and Flag and IntFlag, whose members combine with | & ^ and ~. +auto() picks a member's value, member() and nonmember() say what is and +is not a member, unique() refuses aliases, and the FlagBoundary values +STRICT, CONFORM, EJECT and KEEP say what a Flag does with bits it has no +member for. The functional form, Enum('Animal', 'ANT BEE'), makes a +class from a list of names. + +Three things differ from CPython. A class body here runs before its +names reach the namespace EnumType prepares, so a name auto() gave a +value to is still the auto object when the body itself reads it: AB = +A | B works with explicit values and not with auto() ones. For the same +reason a name the body binds twice keeps its last binding, where CPython +refuses the second. And __members__ is a dict, a copy, where CPython +answers a read-only mapping proxy. + +@author [Jon Ruttan](jonruttan@gmail.com) +@copyright 2026 Jon Ruttan +@license MIT No Attribution (MIT-0) +""" + +__all__ = ['EnumType', 'EnumMeta', 'EnumDict', 'Enum', 'ReprEnum', + 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'FlagBoundary', + 'STRICT', 'CONFORM', 'EJECT', 'KEEP', 'auto', 'member', + 'nonmember', 'unique'] + +# Enum, ReprEnum and Flag are named before they exist, so that EnumType +# can tell, while it makes them, that it is making them +Enum = ReprEnum = Flag = None +STRICT = CONFORM = EJECT = KEEP = None + +_NOT_GIVEN = object() +_AUTO = object() +_FUNCTION = type(lambda: None) + + +# -- what the class body says ------------------------------------------------ + +class auto: + """A member value chosen by the class's _generate_next_value_.""" + + def __init__(self, value=_AUTO): + self.value = value + + def __repr__(self): + return 'auto(%r)' % (self.value,) + + +class member: + """Make value a member even though it would not otherwise be one.""" + + def __init__(self, value): + self.value = value + + +class nonmember: + """Keep value out of the members: it stays a plain class attribute.""" + + def __init__(self, value): + self.value = value + + +def _qualname(cls): + """A class's qualified name, or its plain name where none is kept.""" + return getattr(cls, '__qualname__', None) or cls.__name__ + + +def _is_dunder(name): + return (len(name) > 4 and name[:2] == name[-2:] == '__' + and name[2] != '_' and name[-3] != '_') + + +def _is_sunder(name): + return (len(name) > 2 and name[0] == name[-1] == '_' + and name[1] != '_' and name[-2] != '_') + + +def _is_private(class_name, name): + # a name the class body mangled, _Color__x + prefix = '_%s__' % class_name.lstrip('_') + return (name.startswith(prefix) and len(name) > len(prefix) + and not name.endswith('__')) + + +def _is_descriptor(value): + # functions, the three built-in descriptors, and anything whose class + # answers __get__, __set__ or __delete__ are methods, not members + if isinstance(value, (_FUNCTION, staticmethod, classmethod, property)): + return True + kind = type(value) + return (hasattr(kind, '__get__') or hasattr(kind, '__set__') + or hasattr(kind, '__delete__')) + + +# the _sunder_ names a class body may use; every other one is reserved +_SUNDERS = {'_order_', '_generate_next_value_', '_numeric_repr_', + '_missing_', '_ignore_', '_iter_member_', + '_iter_member_by_value_', '_iter_member_by_def_', + '_add_alias_', '_add_value_alias_'} + + +class EnumDict(dict): + """The namespace of an enum's class body. + + It keeps the order members are named in, refuses a name given twice, + and turns each auto() into its value as the name is stored. + """ + + def __init__(self, cls_name=None): + super().__init__() + self._cls_name = cls_name + self._member_names = {} + self._last_values = [] + self._ignore = [] + self._generate_next_value = None + + @property + def member_names(self): + return list(self._member_names) + + def __setitem__(self, key, value): + if _is_sunder(key): + if key not in _SUNDERS: + raise ValueError('_sunder_ names, such as %r, are reserved ' + 'for future Enum use' % (key,)) + if key == '_generate_next_value_': + self._generate_next_value = getattr(value, '__func__', value) + elif key == '_ignore_': + names = value.replace(',', ' ').split() \ + if isinstance(value, str) else list(value) + self._ignore = names + taken = set(names) & set(self._member_names) + if taken: + raise ValueError('_ignore_ cannot specify already set ' + 'names: %r' % (sorted(taken),)) + elif _is_dunder(key): + if key == '__order__': + key = '_order_' + elif key in self._member_names: + # a second definition of a member, as a member or as a method + raise TypeError('%r already defined as %r' % (key, self[key])) + elif key in self._ignore: + pass + elif isinstance(value, nonmember): + value = value.value + elif _is_descriptor(value): + pass + elif self._cls_name is not None and _is_private(self._cls_name, key): + pass + else: + if key in self: + raise TypeError('%r already defined as %r' % (key, self[key])) + if isinstance(value, member): + value = value.value + value = self._settle(key, value) + self._member_names[key] = None + self._last_values.append(value) + super().__setitem__(key, value) + + def _settle(self, key, value): + # an auto(), alone or in a tuple, becomes the value it stands for + if isinstance(value, auto): + return self._next(key, value) + if isinstance(value, tuple) and any(isinstance(v, auto) for v in value): + return tuple(self._next(key, v) if isinstance(v, auto) else v + for v in value) + return value + + def _next(self, key, a): + if a.value is _AUTO: + if self._generate_next_value is None: + raise TypeError('auto() needs a _generate_next_value_') + a.value = self._generate_next_value( + key, 1, len(self._member_names), self._last_values[:]) + return a.value + + def update(self, other=(), **kwds): + items = other.items() if hasattr(other, 'items') else other + for key, value in items: + self[key] = value + for key, value in kwds.items(): + self[key] = value + + +# -- helpers on classes ------------------------------------------------------ + +def _lineage(cls): + # cls and its bases, each once, in the order lookup visits them + seen = [] + + def visit(c): + if c not in seen: + seen.append(c) + for b in c.__bases__: + visit(b) + visit(cls) + return seen + + +_DATA_TYPES = (int, float, complex, str, bytes, bytearray, tuple, list, + dict, set, frozenset) + + +def _is_enum_class(c): + return isinstance(c, EnumType) + + +def _is_flag_class(c): + return Flag is not None and issubclass(c, Flag) + + +def _bits(n, width): + # n in two's complement, sign bit apart: 0b0 0111, 0b1 1000 + if n < 0: + digits = format((1 << width) + n, 'b').zfill(width) + return '0b1 ' + digits[-width:] + return '0b0 ' + format(n, 'b').zfill(width) + + +def _single_bit(n): + return n > 0 and n & (n - 1) == 0 + + +def _value_str(self): + return str(self._value_) + + +def _value_format(self, spec): + return format(self._value_, spec) + + +# -- the metaclass ----------------------------------------------------------- + +class EnumType(type): + """The metaclass of every enum: it makes the members, and the class + answers len, iteration, in, [name] and (value) through it.""" + + @classmethod + def __prepare__(metacls, cls, bases, **kwds): + metacls._refuse_extending_(cls, bases) + ns = EnumDict(cls) + member_type, first_enum = metacls._get_mixins_(cls, bases) + if first_enum is not None: + ns._generate_next_value = getattr( + first_enum, '_generate_next_value_', None) + return ns + + def __new__(metacls, cls, bases, classdict, *, boundary=None, **kwds): + if not isinstance(classdict, EnumDict): + # a namespace someone built by hand: let EnumDict judge it + judged = EnumDict(cls) + judged._generate_next_value = getattr( + metacls._get_mixins_(cls, bases)[1], + '_generate_next_value_', None) + judged.update(classdict) + classdict = judged + names = list(classdict._member_names) + bad = [n for n in names if n in ('mro', '')] + if bad: + raise ValueError('invalid enum member name(s) %s' + % ', '.join(repr(n) for n in bad)) + member_type, first_enum = metacls._get_mixins_(cls, bases) + make, keep_new, use_args = metacls._find_new_( + classdict, member_type, first_enum) + + values = {} + body = {} + for key, value in classdict.items(): + if key in classdict._member_names: + values[key] = value + elif key not in classdict._ignore and key != '_ignore_': + body[key] = value + order = body.pop('_order_', None) + gnv = body.get('_generate_next_value_') + if isinstance(gnv, _FUNCTION): + body['_generate_next_value_'] = staticmethod(gnv) + + body['_new_member_'] = make + body['_use_args_'] = use_args + body['_member_names_'] = [] + body['_member_map_'] = {} + body['_value2member_map_'] = {} + body['_unhashable_values_'] = [] + body['_member_type_'] = member_type + if boundary is None and first_enum is not None: + boundary = getattr(first_enum, '_boundary_', None) + body['_boundary_'] = boundary + body['_by_def_'] = False + + enum_class = super().__new__(metacls, cls, bases, body, **kwds) + + for name, value in values.items(): + enum_class._add_member_(name, value) + + if Enum is not None: + # lookups go through Enum.__new__; a __new__ the body wrote + # makes members and is kept as __new_member__ + if keep_new: + type.__setattr__(enum_class, '__new_member__', make) + type.__setattr__(enum_class, '__new__', Enum.__dict__['__new__']) + metacls._fit_methods_(enum_class, body, member_type, first_enum, + bases) + if _is_flag_class(enum_class): + metacls._fit_flag_(enum_class) + + if order is not None: + if isinstance(order, str): + order = order.replace(',', ' ').split() + if order != enum_class._member_names_: + raise TypeError('member order does not match _order_:\n' + ' %r\n %r' + % (enum_class._member_names_, order)) + return enum_class + + # how the class is made ................................................... + + @classmethod + def _refuse_extending_(metacls, cls, bases): + for base in bases: + for c in _lineage(base): + if _is_enum_class(c) and c._member_names_: + raise TypeError(' cannot extend %r' % (cls, c)) + + @classmethod + def _get_mixins_(metacls, cls, bases): + if not bases: + return object, Enum + first_enum = bases[-1] + if not _is_enum_class(first_enum): + raise TypeError('new enumerations should be created as ' + '`EnumName([mixin_type, ...] [data_type,] ' + 'enum_type)`') + return metacls._find_data_type_(cls, bases) or object, first_enum + + @classmethod + def _find_data_type_(metacls, cls, bases): + found = [] + for base in bases: + nearest = None + for c in _lineage(base): + if c is object: + continue + if _is_enum_class(c): + if c._member_type_ is not object: + found.append(c._member_type_) + break + continue + if c in _DATA_TYPES or '__new__' in c.__dict__: + found.append(nearest or c) + break + nearest = nearest or c + kinds = [] + for k in found: + if k not in kinds: + kinds.append(k) + if len(kinds) > 1: + raise TypeError('too many data types for %r: %r' % (cls, kinds)) + return kinds[0] if kinds else None + + @classmethod + def _find_new_(metacls, classdict, member_type, first_enum): + # the __new__ that makes members, whether it was written here, by an + # enum this one extends, or by the data type + written = classdict.get('__new__') + keep = first_enum is not None and written is not None + if written is None: + plain = (None, getattr(object, '__new__', None)) + if Enum is not None: + plain = plain + (Enum.__dict__['__new__'], Enum.__new__) + for name in ('__new_member__', '__new__'): + for kind in (member_type, first_enum): + found = getattr(kind, name, None) + # a data type's own __new__ makes its members, even + # where it is object's, which builds the data type's + # value from the arguments + if found is not None and name == '__new__' \ + and kind is member_type and kind is not object: + written = found + break + if found not in plain: + written = found + break + if written is not None: + break + else: + written = object.__new__ + use_args = written is not object.__new__ or member_type is not object + return written, keep, use_args + + @classmethod + def _fit_methods_(metacls, enum_class, body, member_type, first_enum, + bases): + # a mixed-in data type does not supply an enum's repr, str or + # format unless the enum is a ReprEnum, whose str and format are + # the data type's + for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): + if name in body: + continue + found = getattr(enum_class, name, None) + if found is not None and found in ( + getattr(member_type, name, None), + getattr(object, name, None)): + type.__setattr__(enum_class, name, getattr(first_enum, name)) + if ReprEnum is not None and ReprEnum in bases: + if member_type is object: + raise TypeError('ReprEnum subclasses must be mixed with a ' + 'data type (i.e. int, str, float, etc.)') + if '__format__' not in body: + fmt = getattr(member_type, '__format__', None) + if fmt is None or fmt is getattr(object, '__format__', None): + fmt = _value_format + type.__setattr__(enum_class, '__format__', fmt) + if '__str__' not in body: + plain = (None, getattr(object, '__str__', None), + getattr(object, '__repr__', None)) + text = getattr(member_type, '__str__', None) + if text in plain: + text = getattr(member_type, '__repr__', None) + if text in plain: + text = _value_str + type.__setattr__(enum_class, '__str__', text) + + @classmethod + def _fit_flag_(metacls, enum_class): + singles = everything = 0 + last = None + in_order = True + for m in enum_class._member_map_.values(): + v = m._value_ + everything |= v + if _single_bit(v): + singles |= v + if last is not None and v < last: + in_order = False + last = v + type.__setattr__(enum_class, '_flag_mask_', everything) + type.__setattr__(enum_class, '_singles_mask_', singles) + type.__setattr__(enum_class, '_all_bits_', + 2 ** everything.bit_length() - 1) + type.__setattr__(enum_class, '_by_def_', not in_order) + # Flag's operators come before a data type's: IntFlag's | is + # Flag's, though int's is nearer + for op in ('__or__', '__and__', '__xor__', '__ror__', '__rand__', + '__rxor__', '__invert__'): + if op not in enum_class.__dict__: + type.__setattr__(enum_class, op, Flag.__dict__[op]) + + def _add_member_(cls, name, value): + args = value if isinstance(value, tuple) else (value,) + if cls._member_type_ is tuple: + args = (args,) + made = cls._new_member_(cls, *args) if cls._use_args_ \ + else cls._new_member_(cls) + if not hasattr(made, '_value_'): + if cls._member_type_ is object: + made._value_ = value + else: + try: + made._value_ = cls._member_type_(*args) + except Exception: + raise TypeError('_value_ not set in __new__, unable to ' + 'create it') from None + value = made._value_ + made._name_ = name + made.__objclass__ = cls + made.__init__(*args) + made._sort_order_ = len(cls._member_names_) + + same = cls._known_(value) + if same is not None: + # an alias: the name reaches the member that has the value + cls._member_map_[name] = same + type.__setattr__(cls, name, same) + return + if not _is_flag_class(cls) or _single_bit(value): + cls._member_names_.append(name) + cls._member_map_[name] = made + try: + cls._value2member_map_[value] = made + except TypeError: + cls._unhashable_values_.append(value) + type.__setattr__(cls, name, made) + + def _known_(cls, value): + # the member already holding value, or None + try: + return cls._value2member_map_.get(value) + except TypeError: + for m in cls._member_map_.values(): + if m._value_ == value: + return m + return None + + # what the class answers ................................................. + + def __call__(cls, value, names=_NOT_GIVEN, *, module=None, qualname=None, + type=None, start=1, boundary=None): + if names is _NOT_GIVEN: + return cls.__new__(cls, value) + return cls._create_(value, names, module=module, qualname=qualname, + type=type, start=start, boundary=boundary) + + def _create_(cls, class_name, names, *, module=None, qualname=None, + type=None, start=1, boundary=None): + metacls = cls.__class__ + bases = (cls,) if type is None else (type, cls) + first_enum = metacls._get_mixins_(class_name, bases)[1] + ns = metacls.__prepare__(class_name, bases) + if isinstance(names, str): + names = names.replace(',', ' ').split() + if isinstance(names, (list, tuple)) and names \ + and isinstance(names[0], str): + # bare names: their values come from _generate_next_value_ + pairs = [] + seen = [] + for count, name in enumerate(names): + value = first_enum._generate_next_value_( + name, start, count, seen[:]) + seen.append(value) + pairs.append((name, value)) + names = pairs + for item in (names or ()): + if isinstance(item, str): + ns[item] = names[item] + else: + ns[item[0]] = item[1] + made = metacls.__new__(metacls, class_name, bases, ns, + boundary=boundary) + if module is not None: + made.__module__ = module + if qualname is not None: + made.__qualname__ = qualname + return made + + def __bool__(cls): + return True + + def __contains__(cls, value): + if isinstance(value, cls): + return True + try: + return value in cls._value2member_map_ \ + or value in cls._unhashable_values_ + except TypeError: + return value in cls._unhashable_values_ + + def __getitem__(cls, name): + return cls._member_map_[name] + + def __iter__(cls): + return (cls._member_map_[name] for name in cls._member_names_) + + def __reversed__(cls): + return (cls._member_map_[name] + for name in reversed(cls._member_names_)) + + def __len__(cls): + return len(cls._member_names_) + + @property + def __members__(cls): + return dict(cls._member_map_) + + def __repr__(cls): + if _is_flag_class(cls): + return '' % (cls.__name__,) + return '' % (cls.__name__,) + + def __setattr__(cls, name, value): + if name in cls.__dict__.get('_member_map_', {}): + raise AttributeError('cannot reassign member %r' % (name,)) + super().__setattr__(name, value) + + def __delattr__(cls, name): + if name in cls._member_map_: + raise AttributeError('%r cannot delete member %r.' + % (cls.__name__, name)) + super().__delattr__(name) + + +EnumMeta = EnumType + + +# -- the enums --------------------------------------------------------------- + +class Enum(metaclass=EnumType): + """Named constants: subclass it and name the members in the body. + + Members are reached as Color.RED, Color(1) or Color['RED'], and each + has .name and .value. + """ + + def __new__(cls, value): + # Color(1): find the member that has value, never make one + if type(value) is cls: + return value + found = cls._known_(value) + if found is not None: + return found + for m in cls._member_map_.values(): + if m._value_ == value: + return m + failure = None + try: + answer = cls._missing_(value) + except Exception as e: + failure = e + answer = None + if isinstance(answer, cls): + return answer + if _is_flag_class(cls) and cls._boundary_ is EJECT \ + and isinstance(answer, int): + return answer + invalid = ValueError('%r is not a valid %s' + % (value, _qualname(cls))) + if failure is None: + if answer is None: + raise invalid + failure = TypeError('error in %s._missing_: returned %r instead ' + 'of None or a valid member' + % (cls.__name__, answer)) + raise failure + + def __init__(self, *args, **kwds): + pass + + @staticmethod + def _generate_next_value_(name, start, count, last_values): + """One more than the largest value so far, or start for the first.""" + if not last_values: + return start + try: + largest = sorted(last_values)[-1] + except TypeError: + raise TypeError('unable to sort non-numeric values') from None + try: + return largest + 1 + except TypeError: + raise TypeError('unable to increment %r' % (largest,)) from None + + @classmethod + def _missing_(cls, value): + return None + + def __repr__(self): + return '<%s.%s: %r>' % (self.__class__.__name__, self._name_, + self._value_) + + def __str__(self): + return '%s.%s' % (self.__class__.__name__, self._name_) + + def __format__(self, spec): + return format(str(self), spec) + + def __hash__(self): + return hash(self._name_) + + def __reduce_ex__(self, proto): + return self.__class__, (self._value_,) + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + @property + def name(self): + """The member's name.""" + return self._name_ + + @property + def value(self): + """The member's value.""" + return self._value_ + + +class ReprEnum(Enum): + """An enum whose str() and format() are its data type's; only repr() + shows the member.""" + + +class IntEnum(int, ReprEnum): + """An enum whose members are ints as well.""" + + +class StrEnum(str, ReprEnum): + """An enum whose members are strs as well; auto() gives the lowercased + name.""" + + def __new__(cls, *values): + if len(values) > 3: + raise TypeError('too many arguments for str(): %r' % (values,)) + if len(values) == 1 and not isinstance(values[0], str): + raise TypeError('%r is not a string' % (values[0],)) + if len(values) >= 2 and not isinstance(values[1], str): + raise TypeError('encoding must be a string, not %r' + % (values[1],)) + if len(values) == 3 and not isinstance(values[2], str): + raise TypeError('errors must be a string, not %r' % (values[2],)) + text = str(*values) + made = str.__new__(cls, text) + made._value_ = text + return made + + @staticmethod + def _generate_next_value_(name, start, count, last_values): + return name.lower() + + +class FlagBoundary(StrEnum): + """What a Flag does with a value that has bits no member names: + STRICT refuses it, CONFORM drops the bits, EJECT answers a plain int, + and KEEP keeps them.""" + STRICT = auto() + CONFORM = auto() + EJECT = auto() + KEEP = auto() + + +STRICT, CONFORM, EJECT, KEEP = FlagBoundary + + +class Flag(Enum, boundary=STRICT): + """An enum of bits: members combine with | & ^ and ~, and a + combination is a member too, named for the members it holds.""" + + _numeric_repr_ = repr + + @staticmethod + def _generate_next_value_(name, start, count, last_values): + """The next power of two above every value so far.""" + if not count: + return start if start is not None else 1 + largest = max(last_values) + try: + top = largest.bit_length() - 1 + except Exception: + raise TypeError('invalid flag value %r' % (largest,)) from None + return 2 ** (top + 1) + + @classmethod + def _iter_member_by_value_(cls, value): + # the single-bit members within value, smallest first + bit = 1 + while bit <= value: + if value & bit: + m = cls._value2member_map_.get(bit) + # a named member, not a combination made on the way + if m is not None and m._name_ in cls._member_map_: + yield m + bit <<= 1 + + @classmethod + def _iter_member_by_def_(cls, value): + # the same members, in the order the class named them + return iter(sorted(cls._iter_member_by_value_(value), + key=lambda m: m._sort_order_)) + + @classmethod + def _iter_member_(cls, value): + if cls._by_def_: + return cls._iter_member_by_def_(value) + return cls._iter_member_by_value_(value) + + @classmethod + def _missing_(cls, value): + # a combination of members, made once and kept, or a value the + # boundary refuses, trims or keeps + if not isinstance(value, int): + raise ValueError('%r is not a valid %s' % (value, _qualname(cls))) + mask = cls._flag_mask_ + all_bits = cls._all_bits_ + outside = not (~all_bits <= value <= all_bits) \ + or value & (all_bits ^ mask) + if outside: + boundary = cls._boundary_ + if boundary is STRICT: + width = max(value.bit_length(), mask.bit_length()) + raise ValueError('%r invalid value %r\n given %s\n' + ' allowed %s' + % (cls, value, _bits(value, width), + _bits(mask, width))) + if boundary is CONFORM: + value = value & mask + elif boundary is EJECT: + return value + elif boundary is KEEP and value < 0: + value = max(all_bits + 1, 2 ** value.bit_length()) + value + asked = None + if value < 0: + asked = value + value = all_bits + 1 + value + + if cls._member_type_ is object: + made = object.__new__(cls) + else: + made = cls._member_type_.__new__(cls, value) + if not hasattr(made, '_value_'): + made._value_ = value + + held = [] + covered = 0 + for m in cls._iter_member_(value & cls._singles_mask_): + held.append(m) + covered |= m._value_ + rest = value & ~cls._singles_mask_ + if rest: + for m in cls._member_map_.values(): + v = m._value_ + if all(m is not h for h in held) and v and v & value == v \ + and v & ~covered: + held.append(m) + covered |= v + unknown = value & ~covered + if not covered: + made._name_ = None + else: + made._name_ = '|'.join(m._name_ for m in held) + if unknown: + if cls._boundary_ is STRICT: + raise ValueError('%r: no members with value %r' + % (cls, unknown)) + made._name_ += '|' + cls._numeric_repr_(unknown) + made = cls._value2member_map_.setdefault(value, made) + if asked is not None: + cls._value2member_map_[asked] = made + return made + + def __contains__(self, other): + if not isinstance(other, self.__class__): + raise TypeError("unsupported operand type(s) for 'in': %r and %r" + % (_qualname(type(other)), + _qualname(self.__class__))) + return other._value_ & self._value_ == other._value_ + + def __iter__(self): + return iter(list(self._iter_member_(self._value_))) + + def __len__(self): + return self._value_.bit_count() + + def __repr__(self): + name = self.__class__.__name__ + if self._name_ is None: + return '<%s: %r>' % (name, self._value_) + return '<%s.%s: %r>' % (name, self._name_, self._value_) + + def __str__(self): + name = self.__class__.__name__ + if self._name_ is None: + return '%s(%r)' % (name, self._value_) + return '%s.%s' % (name, self._name_) + + def __bool__(self): + return bool(self._value_) + + def _operand_bits(self, other): + # other's value when it can combine with this flag, else None + if isinstance(other, self.__class__): + return other._value_ + if self._member_type_ is not object \ + and isinstance(other, self._member_type_): + return other + return None + + def __or__(self, other): + bits = self._operand_bits(other) + if bits is None: + return NotImplemented + return self.__class__(self._value_ | bits) + + def __and__(self, other): + bits = self._operand_bits(other) + if bits is None: + return NotImplemented + return self.__class__(self._value_ & bits) + + def __xor__(self, other): + bits = self._operand_bits(other) + if bits is None: + return NotImplemented + return self.__class__(self._value_ ^ bits) + + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + + def __invert__(self): + if self._boundary_ in (EJECT, KEEP): + return self.__class__(~self._value_) + return self.__class__(self._singles_mask_ & ~self._value_) + + +class IntFlag(int, ReprEnum, Flag, boundary=KEEP): + """A Flag whose members are ints as well; bits with no member are + kept.""" + + # Flag's own versions, named here so that they come before Enum's + # whichever way a lookup walks the bases + __repr__ = Flag.__dict__['__repr__'] + _missing_ = Flag.__dict__['_missing_'] + _generate_next_value_ = Flag.__dict__['_generate_next_value_'] + + +# -- checking an enum -------------------------------------------------------- + +def unique(enumeration): + """Refuse an enum in which two names share a value.""" + aliases = ['%s -> %s' % (name, m._name_) + for name, m in enumeration.__members__.items() + if name != m._name_] + if aliases: + raise ValueError('duplicate values found in %r: %s' + % (enumeration, ', '.join(aliases))) + return enumeration diff --git a/tests/specs/D16-enum.spec.md b/tests/specs/D16-enum.spec.md new file mode 100644 index 0000000..7a8dd8b --- /dev/null +++ b/tests/specs/D16-enum.spec.md @@ -0,0 +1,116 @@ +# enum: sets of named constants + +`stdlib/enum.py`. Each expected output is a python3.14 run of the same +program. + +### an Enum's members, reached by name, value and iteration + +```python +(python-run "from enum import Enum, auto, unique\nclass Color(Enum):\n RED = 1\n GREEN = 2\n BLUE = 3\n CRIMSON = 1\nprint(Color.RED, repr(Color.RED), Color.RED.name, Color.RED.value)\nprint(Color(2), Color['BLUE'], Color.CRIMSON is Color.RED, type(Color.RED).__name__)\nprint(list(Color), len(Color), list(reversed(Color)))\nprint(list(Color.__members__), Color.RED in Color, 1 in Color, 'RED' in Color)\nprint(repr(Color), isinstance(Color.GREEN, Color), type(Color).__name__, bool(Color))\nprint(Color.RED == Color.RED, Color.RED == 1, Color.RED != Color.GREEN, hash(Color.RED) == hash('RED'))\nprint({Color.RED: 'r'}[Color.CRIMSON], sorted(Color, key=lambda c: c.value))\nprint(format(Color.RED), f'{Color.GREEN}', '%s' % Color.BLUE, f'{Color.RED:>12}|')\nclass Step(Enum):\n ONE = auto()\n TWO = auto()\n TEN = 10\n ELEVEN = auto()\nprint(list(Step), [s.value for s in Step])\nclass Planet(Enum):\n EARTH = (5.97, 6.37)\n MARS = (0.642, 3.39)\n def __init__(self, mass, radius):\n self.mass = mass\n self.radius = radius\n def surface(self):\n return round(self.mass / self.radius ** 2, 3)\nprint(Planet.EARTH.value, Planet.EARTH.mass, Planet((0.642, 3.39)), Planet.MARS.surface())\n") +``` +--- +```output +Color.RED RED 1 +Color.GREEN Color.BLUE True Color +[, , ] 3 [, , ] +['RED', 'GREEN', 'BLUE', 'CRIMSON'] True True False + True EnumType True +True False True True +r [, , ] +Color.RED Color.GREEN Color.BLUE Color.RED| +[, , , ] [1, 2, 10, 11] +(5.97, 6.37) 5.97 Planet.MARS 0.056 +``` + +### what an enum refuses, and what _missing_ and unique decide + +```python +(python-run "from enum import Enum, unique\ndef show(f):\n try:\n print(repr(f()))\n except Exception as e:\n print(type(e).__name__, e)\nclass Color(Enum):\n RED = 1\n GREEN = 2\n CRIMSON = 1\nshow(lambda: Color(5))\nshow(lambda: Color['PURPLE'])\nshow(lambda: Color.RED < Color.GREEN)\ndef extend():\n class More(Color):\n BLUE = 3\nshow(extend)\ndef reassign():\n Color.RED = 5\nshow(reassign)\ndef remove():\n del Color.RED\nshow(remove)\nshow(lambda: unique(Color))\ndef reserved():\n class D(Enum):\n _foo_ = 1\nshow(reserved)\ndef badname():\n class D(Enum):\n mro = 1\nshow(badname)\ndef badorder():\n class D(Enum):\n _order_ = 'Y X'\n X = 1\n Y = 2\nshow(badorder)\nclass Missing(Enum):\n A = 1\n @classmethod\n def _missing_(cls, value):\n if isinstance(value, str):\n return cls.A\n if value == 0:\n return 'zero'\n return None\nshow(lambda: Missing('anything'))\nshow(lambda: Missing(0))\nshow(lambda: Missing(9))\n@unique\nclass Fine(Enum):\n A = 1\n B = 2\nprint(list(Fine))\n") +``` +--- +```output +ValueError 5 is not a valid Color +KeyError 'PURPLE' +TypeError '<' not supported between instances of 'Color' and 'Color' +TypeError cannot extend +AttributeError cannot reassign member 'RED' +AttributeError 'Color' cannot delete member 'RED'. +ValueError duplicate values found in : CRIMSON -> RED +ValueError _sunder_ names, such as '_foo_', are reserved for future Enum use +ValueError invalid enum member name(s) 'mro' +TypeError member order does not match _order_: + ['X', 'Y'] + ['Y', 'X'] + +TypeError error in Missing._missing_: returned 'zero' instead of None or a valid member +ValueError 9 is not a valid Missing +[, ] +``` + +### IntEnum, StrEnum and a mixed-in data type + +```python +(python-run "from enum import IntEnum, StrEnum, Enum, auto\nclass Num(IntEnum):\n ONE = 1\n TWO = auto()\n THREE = 3\nprint(Num.TWO, repr(Num.TWO), str(Num.TWO), format(Num.TWO, '03d'), f'{Num.ONE}')\nprint(Num.ONE + 1, Num.TWO * 3, Num.ONE == 1, Num.ONE < Num.THREE, Num.THREE > 2, hash(Num.ONE) == hash(1))\nprint(Num(2), sorted([Num.THREE, Num.ONE]), [1, 2, 3, 4][Num.TWO], isinstance(Num.ONE, int), int(Num.THREE))\nprint(list(Num), Num['THREE'], 2 in Num, type(Num.ONE + 0).__name__, max(Num))\nclass Shade(StrEnum):\n LIGHT = auto()\n DARK = 'dark-ish'\nprint(Shade.LIGHT, repr(Shade.LIGHT), format(Shade.DARK), Shade.LIGHT + '!', Shade.LIGHT.upper())\nprint(Shade.LIGHT == 'light', Shade('dark-ish'), isinstance(Shade.DARK, str), len(Shade.DARK), list(Shade))\ndef badstr():\n class S(StrEnum):\n A = 1\ntry:\n badstr()\nexcept TypeError as e:\n print('TypeError', e)\nclass Mixed(int, Enum):\n A = 1\n B = 2\nprint(Mixed.A, repr(Mixed.B), Mixed.A + Mixed.B, format(Mixed.A))\n") +``` +--- +```output +2 2 002 1 +2 6 True True True True +2 [, ] 3 True 3 +[, , ] 3 True int 3 +light dark-ish light! LIGHT +True dark-ish True 8 [, ] +TypeError 1 is not a string +Mixed.A 3 Mixed.A +``` + +### a Flag's members combine, and its boundary judges stray bits + +```python +(python-run "from enum import Flag, auto, CONFORM, EJECT\ndef show(f):\n try:\n print(repr(f()))\n except Exception as e:\n print(type(e).__name__, e)\nclass Perm(Flag):\n R = 4\n W = 2\n X = 1\nprint(Perm.R | Perm.W, repr(Perm.R | Perm.W), (Perm.R | Perm.W).name, list(Perm.R | Perm.X))\nprint(len(Perm.R | Perm.X), Perm.R in (Perm.R | Perm.W), Perm.X in Perm.R, bool(Perm(0)), str(Perm(0)))\nprint(repr(Perm(0)), Perm(0).name, repr(~Perm.R), repr(Perm(7)), repr(Perm), list(Perm), 1 in Perm)\nshow(lambda: Perm(8))\nshow(lambda: Perm.R | 1)\nshow(lambda: 2 in Perm.R)\nclass F(Flag):\n A = auto()\n B = auto()\n C = auto()\n AB = 3\nprint(list(F), repr(F.AB), repr(F(3)), repr(F(7)), list(F.__members__), repr(F.A & F.B), repr(F.A ^ F(3)))\nclass G(Flag, boundary=CONFORM):\n A = 1\n B = 2\nclass H(Flag, boundary=EJECT):\n A = 1\n B = 2\nprint(repr(G(7)), repr(H(7)), repr(~G.A))\n") +``` +--- +```output +Perm.R|W R|W [, ] +2 True False False Perm(0) + None [, , ] True +ValueError invalid value 8 + given 0b0 1000 + allowed 0b0 0111 +TypeError unsupported operand type(s) for |: 'Perm' and 'int' +TypeError unsupported operand type(s) for 'in': 'int' and 'Perm' +[, , ] ['A', 'B', 'C', 'AB'] + 7 +``` + +### an IntFlag is an int, and keeps the bits it has no member for + +```python +(python-run "from enum import IntFlag, auto\nclass Perm(IntFlag):\n R = 4\n W = 2\n X = 1\nprint(Perm.R | Perm.W, repr(Perm.R | Perm.W), repr(Perm(8)), repr(Perm.R | 8), repr(~Perm.R))\nprint(Perm.R + 1, str(Perm.R | Perm.W), format(Perm.R), repr(Perm(9)), list(Perm(9)), repr(Perm.R | 1))\nclass I(IntFlag):\n A = auto()\n B = auto()\nprint(repr(I(7)), repr(I.A | I.B), repr(I.A & 3), repr(I.A ^ 1), repr(3 | I.A), I.A + I.B, -I.A)\nprint(repr(~I(7)), repr(I(0)), bool(I(0)), I.A == 1, list(I(7)), repr(I), I(7).name, I(3).name)\nprint(isinstance(I.A, int), I.B << 1, I.A in I(3), hash(I.B) == hash(2))\n") +``` +--- +```output +6 +5 6 4 [] + 3 -1 + False True [, ] A|B|4 A|B +True 4 True True +``` + +### the functional form, methods and properties, and copying + +```python +(python-run "from enum import Enum, IntEnum, Flag, StrEnum, nonmember, member\nAnimal = Enum('Animal', 'ANT BEE CAT')\nprint(repr(Animal), list(Animal), Animal.BEE.value)\nPairs = Enum('Pairs', [('X', 5), ('Y', 6)])\nprint(list(Pairs), list(Enum('Mapped', {'P': 'p', 'Q': 'q'})))\nprint(list(IntEnum('Count', 'ONE, TWO')), list(Enum('Start', 'A B', start=10)))\nBits = Flag('Bits', 'X Y Z')\nprint(list(Bits), repr(Bits.X | Bits.Z))\nprint(list(StrEnum('Names', 'AB CD')))\nclass Shape(Enum):\n SQUARE = 4\n TRIANGLE = 3\n @property\n def sides(self):\n return self.value\n def describe(self):\n return '%s has %d sides' % (self.name.lower(), self.sides)\n @classmethod\n def biggest(cls):\n return max(cls, key=lambda s: s.value)\n COLORS = nonmember(['red'])\nprint(Shape.SQUARE.describe(), Shape.biggest(), Shape.SQUARE.sides, list(Shape)[:2], Shape.COLORS)\nclass Holder(Enum):\n SIZE = member(len)\n PLAIN = 2\nprint(list(Holder.__members__), Holder.SIZE.value is len)\nclass Base(Enum):\n def hello(self):\n return 'hello ' + self.name\nclass Child(Base):\n A = 1\nprint(Child.A.hello(), list(Child))\nimport copy\nprint(copy.copy(Shape.SQUARE) is Shape.SQUARE, copy.deepcopy(Shape.TRIANGLE) is Shape.TRIANGLE)\n") +``` +--- +```output + [, , ] 2 +[, ] [, ] +[, ] [, ] +[, , ] +[, ] +square has 4 sides Shape.SQUARE 4 [, ] ['red'] +['SIZE', 'PLAIN'] True +hello A [] +True True +```