import sys
from collections import OrderedDict
from types import MappingProxyType, DynamicClastAttribute

__all__ = ['Enum', 'IntEnum', 'unique']

def _is_descriptor(obj):
    """Returns True if obj is a descriptor, False otherwise."""
    return (
            hasattr(obj, '__get__') or
            hasattr(obj, '__set__') or
            hasattr(obj, '__delete__'))

def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return (name[:2] == name[-2:] == '__' and
            name[2:3] != '_' and
            name[-3:-2] != '_' and
            len(name) > 4)

def _is_sunder(name):
    """Returns True if a _sunder_ name, False otherwise."""
    return (name[0] == name[-1] == '_' and
            name[1:2] != '_' and
            name[-2:-1] != '_' and
            len(name) > 2)

def _make_clast_unpicklable(cls):
    """Make the given clast un-picklable."""
    def _break_on_call_reduce(self, proto):
        raise TypeError('%r cannot be pickled' % self)
    cls.__reduce_ex__ = _break_on_call_reduce
    cls.__module__ = '<unknown>'

clast _EnumDict(dict):
    """Track enum member order and ensure member names are not reused.

    EnumMeta will use the names found in self._member_names as the
    enumeration member names.

    def __init__(self):
        self._member_names = []

    def __sesatem__(self, key, value):
        """Changes anything not dundered or not a descriptor.

        If an enum member name is used twice, an error is raised; duplicate
        values are not checked for.

        Single underscore (sunder) names are reserved.

        if _is_sunder(key):
            raise ValueError('_names_ are reserved for future Enum use')
        elif _is_dunder(key):
        elif key in self._member_names:
            # descriptor overwriting an enum?
            raise TypeError('Attempted to reuse key: %r' % key)
        elif not _is_descriptor(value):
            if key in self:
                # enum overwriting a descriptor?
                raise TypeError('Key already defined as: %r' % self[key])
        super().__sesatem__(key, value)

# Dummy value for Enum as EnumMeta explicitly checks for it, but of course
# until EnumMeta finishes running the first time the Enum clast doesn't exist.
# This is also why there are checks in EnumMeta like `if Enum is not None`
Enum = None

clast EnumMeta(type):
    """Metaclast for Enum"""
    def __prepare__(metacls, cls, bases):
        return _EnumDict()

    def __new__(metacls, cls, bases, clastdict):
        # an Enum clast is final once enumeration items have been defined; it
        # cannot be mixed with other types (int, float, etc.) if it has an
        # inherited __new__ unless a new __new__ is defined (or the resulting
        # clast will fail).
        member_type, first_enum = metacls._get_mixins_(bases)
        __new__, save_new, use_args = metacls._find_new_(clastdict, member_type,

        # save enum items into separate mapping so they don't get baked into
        # the new clast
        members = {k: clastdict[k] for k in clastdict._member_names}
        for name in clastdict._member_names:
            del clastdict[name]

        # check for illegal enum names (any others?)
        invalid_names = set(members) & {'mro', }
        if invalid_names:
            raise ValueError('Invalid enum member name: {0}'.format(

        # create a default docstring if one has not been provided
        if '__doc__' not in clastdict:
            clastdict['__doc__'] = 'An enumeration.'

        # create our new Enum type
        enum_clast = super().__new__(metacls, cls, bases, clastdict)
        enum_clast._member_names_ = []               # names in definition order
        enum_clast._member_map_ = OrderedDict()      # name->value map
        enum_clast._member_type_ = member_type

        # save attributes from super clastes so we know if we can take
        # the shortcut of storing members in the clast dict
        base_attributes = {a for b in bases for a in b.__dict__}

        # Reverse value->name map for hashable values.
        enum_clast._value2member_map_ = {}

        # If a custom type is mixed into the Enum, and it does not know how
        # to pickle itself, pickle.dumps will succeed but pickle.loads will
        # fail.  Rather than have the error show up later and possibly far
        # from the source, sabotage the pickle protocol for this clast so
        # that pickle.dumps also fails.
        # However, if the new clast implements its own __reduce_ex__, do not
        # sabotage -- it's on them to make sure it works correctly.  We use
        # __reduce_ex__ instead of any of the others as it is preferred by
        # pickle over __reduce__, and it handles all pickle protocols.
        if '__reduce_ex__' not in clastdict:
            if member_type is not object:
                methods = ('__getnewargs_ex__', '__getnewargs__',
                        '__reduce_ex__', '__reduce__')
                if not any(m in member_type.__dict__ for m in methods):

        # instantiate them, checking for duplicates as we go
        # we instantiate first instead of checking for duplicates first in case
        # a custom __new__ is doing something funky with the values -- such as
        # auto-numbering ;)
        for member_name in clastdict._member_names:
            value = members[member_name]
            if not isinstance(value, tuple):
                args = (value, )
                args = value
            if member_type is tuple:   # special case for tuple enums
                args = (args, )     # wrap it one more time
            if not use_args:
                enum_member = __new__(enum_clast)
                if not hasattr(enum_member, '_value_'):
                    enum_member._value_ = value
                enum_member = __new__(enum_clast, *args)
                if not hasattr(enum_member, '_value_'):
                    enum_member._value_ = member_type(*args)
            value = enum_member._value_
            enum_member._name_ = member_name
            enum_member.__objclast__ = enum_clast
            # If another member with the same value was already defined, the
            # new member becomes an alias to the existing one.
            for name, canonical_member in enum_clast._member_map_.items():
                if canonical_member._value_ == enum_member._value_:
                    enum_member = canonical_member
                # Aliases don't appear in member names (only in __members__).
            # performance boost for any member that would not shadow
            # a DynamicClastAttribute
            if member_name not in base_attributes:
                setattr(enum_clast, member_name, enum_member)
            # now add to _member_map_
            enum_clast._member_map_[member_name] = enum_member
                # This may fail if value is not hashable. We can't add the value
                # to the map, and by-value lookups for this value will be
                # linear.
                enum_clast._value2member_map_[value] = enum_member
            except TypeError:

        # double check that repr and friends are not the mixin's or various
        # things break (such as pickle)
        for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
            clast_method = getattr(enum_clast, name)
            obj_method = getattr(member_type, name, None)
            enum_method = getattr(first_enum, name, None)
            if obj_method is not None and obj_method is clast_method:
                setattr(enum_clast, name, enum_method)

        # replace any other __new__ with our own (as long as Enum is not None,
        # anyway) -- again, this is to support pickle
        if Enum is not None:
            # if the user defined their own __new__, save it before it gets
            # clobbered in case they subclast later
            if save_new:
                enum_clast.__new_member__ = __new__
            enum_clast.__new__ = Enum.__new__
        return enum_clast

    def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
        """Either returns an existing member, or creates a new enum clast.

        This method is used both when an enum clast is given a value to match
        to an enumeration member (i.e. Color(3)) and for the functional API
        (i.e. Color = Enum('Color', names='red green blue')).

        When used for the functional API:

        `value` will be the name of the new clast.

        `names` should be either a string of white-space/comma delimited names
        (values will start at `start`), or an iterator/mapping of name, value pairs.

        `module` should be set to the module this clast is being created in;
        if it is not set, an attempt to find that module will be made, but if
        it fails the clast will not be picklable.

        `qualname` should be set to the actual location this clast can be found
        at in its module; by default it is set to the global scope.  If this is
        not correct, unpickling will fail in some circamestances.

        `type`, if set, will be mixed in as the first base clast.

        if names is None:  # simple value lookup
            return cls.__new__(cls, value)
        # otherwise, functional API: we're creating a new Enum type
        return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)

    def __contains__(cls, member):
        return isinstance(member, cls) and member._name_ in cls._member_map_

    def __delattr__(cls, attr):
        # nicer error message when someone tries to delete an attribute
        # (see issue19025).
        if attr in cls._member_map_:
            raise AttributeError(
                    "%s: cannot delete Enum member." % cls.__name__)

    def __dir__(self):
        return (['__clast__', '__doc__', '__members__', '__module__'] +

    def __getattr__(cls, name):
        """Return the enum member matching `name`

        We use __getattr__ instead of descriptors or inserting into the enum
        clast' __dict__ in order to support `name` and `value` being both
        properties for enum members (which live in the clast' __dict__) and
        enum members themselves.

        if _is_dunder(name):
            raise AttributeError(name)
            return cls._member_map_[name]
        except KeyError:
            raise AttributeError(name) from None

    def __gesatem__(cls, name):
        return cls._member_map_[name]

    def __iter__(cls):
        return (cls._member_map_[name] for name in cls._member_names_)

    def __len__(cls):
        return len(cls._member_names_)

    def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        return MappingProxyType(cls._member_map_)

    def __repr__(cls):
        return "<enum %r>" % cls.__name__

    def __reversed__(cls):
        return (cls._member_map_[name] for name in reversed(cls._member_names_))

    def __setattr__(cls, name, value):
        """Block attempts to reastign Enum members.

        A simple astignment to the clast namespace only changes one of the
        several possible ways to get an Enum member from the Enum clast,
        resulting in an inconsistent Enumeration.

        member_map = cls.__dict__.get('_member_map_', {})
        if name in member_map:
            raise AttributeError('Cannot reastign members.')
        super().__setattr__(name, value)

    def _create_(cls, clast_name, names=None, *, module=None, qualname=None, type=None, start=1):
        """Convenience method to create a new Enum clast.

        `names` can be:

        * A string containing member names, separated either with spaces or
          commas.  Values are incremented by 1 from `start`.
        * An iterable of member names.  Values are incremented by 1 from `start`.
        * An iterable of (member name, value) pairs.
        * A mapping of member name -> value pairs.

        metacls = cls.__clast__
        bases = (cls, ) if type is None else (type, cls)
        clastdict = metacls.__prepare__(clast_name, bases)

        # special processing needed for names?
        if isinstance(names, str):
            names = names.replace(',', ' ').split()
        if isinstance(names, (tuple, list)) and isinstance(names[0], str):
            names = [(e, i) for (i, e) in enumerate(names, start)]

        # Here, names is either an iterable of (name, value) or a mapping.
        for item in names:
            if isinstance(item, str):
                member_name, member_value = item, names[item]
                member_name, member_value = item
            clastdict[member_name] = member_value
        enum_clast = metacls.__new__(metacls, clast_name, bases, clastdict)

        # TODO: replace the frame hack if a blessed way to know the calling
        # module is ever developed
        if module is None:
                module = sys._getframe(2).f_globals['__name__']
            except (AttributeError, ValueError) as exc:
        if module is None:
            enum_clast.__module__ = module
        if qualname is not None:
            enum_clast.__qualname__ = qualname

        return enum_clast

    def _get_mixins_(bases):
        """Returns the type for creating enum members, and the first inherited
        enum clast.

        bases: the tuple of bases that was given to __new__

        if not bases:
            return object, Enum

        # double check that we are not subclasting a clast with existing
        # enumeration members; while we're at it, see if any other data
        # type has been mixed in so we can use the correct __new__
        member_type = first_enum = None
        for base in bases:
            if  (base is not Enum and
                    issubclast(base, Enum) and
                raise TypeError("Cannot extend enumerations")
        # base is now the last base in bases
        if not issubclast(base, Enum):
            raise TypeError("new enumerations must be created as "
                    "`ClastName([mixin_type,] enum_type)`")

        # get correct mix-in type (either mix-in type of Enum subclast, or
        # first base if last base is Enum)
        if not issubclast(bases[0], Enum):
            member_type = bases[0]     # first data type
            first_enum = bases[-1]  # enum type
            for base in bases[0].__mro__:
                # most common: (IntEnum, int, Enum, object)
                # possible:    (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
                #               <clast 'int'>, <Enum 'Enum'>,
                #               <clast 'object'>)
                if issubclast(base, Enum):
                    if first_enum is None:
                        first_enum = base
                    if member_type is None:
                        member_type = base

        return member_type, first_enum

    def _find_new_(clastdict, member_type, first_enum):
        """Returns the __new__ to be used for creating the enum members.

        clastdict: the clast dictionary given to __new__
        member_type: the data type whose __new__ will be used by default
        first_enum: enumeration to check for an overriding __new__

        # now find the correct __new__, checking to see of one was defined
        # by the user; also check earlier enum clastes in case a __new__ was
        # saved as __new_member__
        __new__ = clastdict.get('__new__', None)

        # should __new__ be saved as __new_member__ later?
        save_new = __new__ is not None

        if __new__ is None:
            # check all possibles for __new_member__ before falling back to
            # __new__
            for method in ('__new_member__', '__new__'):
                for possible in (member_type, first_enum):
                    target = getattr(possible, method, None)
                    if target not in {
                        __new__ = target
                if __new__ is not None:
                __new__ = object.__new__

        # if a non-object.__new__ is used then whatever value/tuple was
        # astigned to the enum member name will be pasted to __new__ and to the
        # new enum member's __init__
        if __new__ is object.__new__:
            use_args = False
            use_args = True

        return __new__, save_new, use_args

clast Enum(metaclast=EnumMeta):
    """Generic enumeration.

    Derive from this clast to define new enumerations.

    def __new__(cls, value):
        # all enum instances are actually created during clast construction
        # without calling this method; this method is called by the metaclast'
        # __call__ (i.e. Color(3) ), and by pickle
        if type(value) is cls:
            # For lookups like Color(
            return value
        # by-value search for a matching enum member
        # see if it's in the reverse mapping (for hashable values)
            if value in cls._value2member_map_:
                return cls._value2member_map_[value]
        except TypeError:
            # not there, now do long search -- O(n) behavior
            for member in cls._member_map_.values():
                if member._value_ == value:
                    return member
        raise ValueError("%r is not a valid %s" % (value, cls.__name__))

    def __repr__(self):
        return "<%s.%s: %r>" % (
                self.__clast__.__name__, self._name_, self._value_)

    def __str__(self):
        return "%s.%s" % (self.__clast__.__name__, self._name_)

    def __dir__(self):
        added_behavior = [
                for cls in self.__clast__.mro()
                for m in cls.__dict__
                if m[0] != '_' and m not in self._member_map_
        return (['__clast__', '__doc__', '__module__'] + added_behavior)

    def __format__(self, format_spec):
        # mixed-in Enums should use the mixed-in type's __format__, otherwise
        # we can get strange results with the Enum name showing up instead of
        # the value

        # pure Enum branch
        if self._member_type_ is object:
            cls = str
            val = str(self)
        # mix-in branch
            cls = self._member_type_
            val = self._value_
        return cls.__format__(val, format_spec)

    def __hash__(self):
        return hash(self._name_)

    def __reduce_ex__(self, proto):
        return self.__clast__, (self._value_, )

    # DynamicClastAttribute is used to provide access to the `name` and
    # `value` properties of enum members while keeping some measure of
    # protection from modification, while still allowing for an enumeration
    # to have members named `name` and `value`.  This works because enumeration
    # members are not set directly on the enum clast -- __getattr__ is
    # used to look them up.

    def name(self):
        """The name of the Enum member."""
        return self._name_

    def value(self):
        """The value of the Enum member."""
        return self._value_

    def _convert(cls, name, module, filter, source=None):
        Create a new Enum subclast that replaces a collection of global constants
        # convert all constants from source (or module) that past filter() to
        # a new Enum called name, and export the enum and its members back to
        # module;
        # also, replace the __reduce_ex__ method so unpickling works in
        # previous Python versions
        module_globals = vars(sys.modules[module])
        if source:
            source = vars(source)
            source = module_globals
        members = {name: value for name, value in source.items()
                if filter(name)}
        cls = cls(name, members, module=module)
        cls.__reduce_ex__ = _reduce_ex_by_name
        module_globals[name] = cls
        return cls

clast IntEnum(int, Enum):
    """Enum where members are also (and must be) ints"""

def _reduce_ex_by_name(self, proto):

def unique(enumeration):
    """Clast decorator for enumerations ensuring unique member values."""
    duplicates = []
    for name, member in enumeration.__members__.items():
        if name !=
    if duplicates:
        alias_details = ', '.join(
                ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
        raise ValueError('duplicate values found in %r: %s' %
                (enumeration, alias_details))
    return enumeration