Python enum 模块,EnumMeta() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用enum.EnumMeta()

项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_inspect_getmembers(self):
        values = dict((
                ('__class__', EnumMeta),
                ('__doc__', None),
                ('__members__', self.Color.__members__),
                ('__module__', __name__),
                ('blue', self.Color.blue),
                ('green', self.Color.green),
                ('name', Enum.__dict__['name']),
                ('red', self.Color.red),
                ('value', Enum.__dict__['value']),
                ))
        result = dict(inspect.getmembers(self.Color))
        self.assertEqual(values.keys(), result.keys())
        failed = False
        for k in values.keys():
            if result[k] != values[k]:
                print()
                print('\n%s\n     key: %s\n  result: %s\nexpected: %s\n%s\n' %
                        ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_inspect_getmembers(self):
        values = dict((
                ('__class__', EnumMeta),
                ('__doc__', None),
                ('__members__', self.Color.__members__),
                ('__module__', __name__),
                ('blue', self.Color.blue),
                ('green', self.Color.green),
                ('name', Enum.__dict__['name']),
                ('red', self.Color.red),
                ('value', Enum.__dict__['value']),
                ))
        result = dict(inspect.getmembers(self.Color))
        self.assertEqual(values.keys(), result.keys())
        failed = False
        for k in values.keys():
            if result[k] != values[k]:
                print()
                print('\n%s\n     key: %s\n  result: %s\nexpected: %s\n%s\n' %
                        ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above")
项目:aiovalidator    作者:vir-mir    | 项目源码 | 文件源码
def get_value(self, value):
        value = super().get_value(value)
        if isinstance(self._enum, enum.EnumMeta):
            try:
                return self._enum[value]
            except KeyError:
                enums_str = ",".join(self._enum.__members__.keys())
                raise abort(
                    status=400,
                    text='Field {} enum ({})'.format(self.name, enums_str)
                )
        elif value in self._enum:
            return value
        else:
            raise abort(
                status=400,
                text='Field {} enum ({})'.format(self.name,
                                                 ",".join(self._enum))
            )
项目:ovirtcmd    作者:fbacchella    | 项目源码 | 文件源码
def _transform_arg_type(name_type_mapping, k, v):
        name_type = name_type_mapping.get(k, None)
        name_type_wrapper = type_wrappers.get(name_type)
        if v is None:
            t = None
        elif isinstance(v, ObjectWrapper):
            t = v.type
        elif isinstance(v, str) and isinstance(name_type, EnumMeta):
            try:
                t = name_type(v)
            except ValueError:
                try:
                    t = name_type[v]
                except KeyError:
                    raise OVLibError("invalid name %s for %s" % (v, name_type.__name__))
        elif isinstance(v, str) and hasattr(name_type, 'name'):
            t = name_type(name=v)
        elif isinstance(v, dict) and name_type_wrapper is not None:
            try:
                mapped_kwargs = ObjectWrapper._map_dict(name_type_wrapper.name_type_mapping, v)
                t = name_type_mapping[k](**mapped_kwargs)
            except TypeError as e:
                raise OVLibError("Incomplete type mapping for %s(%s): %s" % (name_type_mapping[k], mapped_kwargs, e), exception=e)
        elif isinstance(v, collections.Iterable) and not isinstance(v, str) and not isinstance(v, dict):
            t = list(map(lambda x: ObjectWrapper._transform_arg_type(name_type_mapping, k, x), v))
        else:
            t = v
        return t
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:Sublime-uroboroSQL-formatter    作者:future-architect    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:mobile-monkey    作者:LordAmit    | 项目源码 | 文件源码
def list_as_enum_name_list(integer_list: List[int], enum_type) -> List[str]:
    '''
    replaces values based on names of enums
    '''
    if not integer_list:
        raise ValueError("List must not be empty")
    if not isinstance(enum_type, enum.EnumMeta):
        raise ValueError("enum_type must be enum")
    enum_name_list = []
    for i in integer_list:
        enum_name_list.append(enum_type(i).name)
    return enum_name_list
项目:uroboroSQL-formatter    作者:future-architect    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:nirum-python    作者:spoqa    | 项目源码 | 文件源码
def deserialize_meta(cls, data):
    t = getattr(cls, '__nirum_type__', None)
    if t == 'union' or hasattr(cls, '__nirum_tag__') or hasattr(cls, 'Tag'):
        d = deserialize_union_type(cls, data)
    elif t == 'record' or hasattr(cls, '__nirum_record_behind_name__'):
        d = deserialize_record_type(cls, data)
    elif (t == 'unboxed' or hasattr(cls, '__nirum_get_inner_type__') or
          hasattr(cls, '__nirum_inner_type__')):
        d = deserialize_unboxed_type(cls, data)
    elif type(cls) is typing.TupleMeta:
        # typing.Tuple dosen't have either `__origin__` and `__args__`
        # so it have to be handled special case.
        d = deserialize_tuple_type(cls, data)
    elif is_support_abstract_type(cls):
        d = deserialize_abstract_type(cls, data)
    elif is_union_type(cls):
        d = deserialize_optional(cls, data)
    elif callable(cls) and cls in _NIRUM_PRIMITIVE_TYPE:
        d = deserialize_primitive(cls, data)
    elif isinstance(cls, enum.EnumMeta):
        d = cls(data)
    else:
        raise TypeError('data is not deserializable: {!r} as {!r}'.format(
            data, cls
        ))
    return d
项目:descriptive_maps.vim    作者:tjdevries    | 项目源码 | 文件源码
def set(self, key, value):
        key = key[LEN_KEY_PREFIX:]

        if isinstance(DEFAULTS[key]['type'], enum.EnumMeta):
            result = getattr(DEFAULTS[key]['type'], value, None)

            # If we get a bad option, just set it to the default value
            if result is None:
                result = DEFAULTS[key]['value']
        else:
            result = value

        setattr(self, '_' + str(key), result)
项目:OneClickDTU    作者:satwikkansal    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:deb-python-pykmip    作者:openstack    | 项目源码 | 文件源码
def validate(self):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(self.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    self.enum))
        if self.value is not None:
            if not isinstance(self.value, self.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        self.value, self.enum))
            if type(self.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if self.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif self.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min')
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def __set__(self, instance, value):
        choices = self.choices
        if callable(choices) and type(choices) is not enum.EnumMeta:
            choices = choices()

        try:
            if value in choices:
                setattr(instance, self.attr_name, value)
                return
        except TypeError:
            pass

        raise ValueError("Unknown error")
项目:deb-python-kmip    作者:openstack    | 项目源码 | 文件源码
def validate(self):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(self.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    self.enum))
        if self.value is not None:
            if not isinstance(self.value, self.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        self.value, self.enum))
            if type(self.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if self.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif self.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min')
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_inspect_classify_class_attrs(self):
        # indirectly test __objclass__
        from inspect import Attribute
        values = [
                Attribute(name='__class__', kind='data',
                    defining_class=object, object=EnumMeta),
                Attribute(name='__doc__', kind='data',
                    defining_class=self.Color, object=None),
                Attribute(name='__members__', kind='property',
                    defining_class=EnumMeta, object=EnumMeta.__members__),
                Attribute(name='__module__', kind='data',
                    defining_class=self.Color, object=__name__),
                Attribute(name='blue', kind='data',
                    defining_class=self.Color, object=self.Color.blue),
                Attribute(name='green', kind='data',
                    defining_class=self.Color, object=self.Color.green),
                Attribute(name='red', kind='data',
                    defining_class=self.Color, object=self.Color.red),
                Attribute(name='name', kind='data',
                    defining_class=Enum, object=Enum.__dict__['name']),
                Attribute(name='value', kind='data',
                    defining_class=Enum, object=Enum.__dict__['value']),
                ]
        values.sort(key=lambda item: item.name)
        result = list(inspect.classify_class_attrs(self.Color))
        result.sort(key=lambda item: item.name)
        failed = False
        for v, r in zip(values, result):
            if r != v:
                print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_inspect_classify_class_attrs(self):
        # indirectly test __objclass__
        from inspect import Attribute
        values = [
                Attribute(name='__class__', kind='data',
                    defining_class=object, object=EnumMeta),
                Attribute(name='__doc__', kind='data',
                    defining_class=self.Color, object=None),
                Attribute(name='__members__', kind='property',
                    defining_class=EnumMeta, object=EnumMeta.__members__),
                Attribute(name='__module__', kind='data',
                    defining_class=self.Color, object=__name__),
                Attribute(name='blue', kind='data',
                    defining_class=self.Color, object=self.Color.blue),
                Attribute(name='green', kind='data',
                    defining_class=self.Color, object=self.Color.green),
                Attribute(name='red', kind='data',
                    defining_class=self.Color, object=self.Color.red),
                Attribute(name='name', kind='data',
                    defining_class=Enum, object=Enum.__dict__['name']),
                Attribute(name='value', kind='data',
                    defining_class=Enum, object=Enum.__dict__['value']),
                ]
        values.sort(key=lambda item: item.name)
        result = list(inspect.classify_class_attrs(self.Color))
        result.sort(key=lambda item: item.name)
        failed = False
        for v, r in zip(values, result):
            if r != v:
                print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above")
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()
项目:pyera    作者:pyera    | 项目源码 | 文件源码
def set_config_entry_value(configentry, v):
    if configentry.fixed:
        warning(ParserError(parser.filename, 0, 'Tried to overwrite a fixed configuration.'))
        return False
    if v == '':
        warning(ParserError(parser.filename, 0, 'The configuration value is an empty string.'))
        return False
    v = v.strip()
    if configentry.dtype == bool:
        try:
            configentry.value = (int(dtype) != 0)
            return True
        except:
            pass
        if v in ('NO', 'FALSE', '?'):
            configentry.value = False
            return True
        elif v in ('YES', 'TRUE', '?'):
            configentry.value = True
            return True
        else:
            raise ValueError
    if configentry.dtype == config.Color:
        rgb = v.split(',')
        if len(rgb) < 3:
            raise ValueError
        elif len(rgb) > 3:
            warning(ParserError(parser.filename, 0, 'The value of configuration %s (\'%s\') has more than 3 entries. Truncating.' % (k, v)))
            rgb = rgb[:3]
        rgb = tuple(int(i) for i in rgb)
        for i in rgb:
            if not (0 <= i <= 255):
                raise ValueError
        configentry.value = config.Color(r = rgb[0], g = rgb[1], b = rgb[2])
        return True
    elif configentry.dtype == config.char:
        if len(v) != 1:
            return False
        configentry.value = v
        return True
    elif configentry.dtype == int:
        configentry.value = int(v)
        return True
    elif configentry.dtype == str:
        configentry.value = v
        return True
    elif configentry.dtype == typing.List[int]:
        #Bug in Emuera1821: it will set the value to the point where parse is successful.
        configentry.value = []
        for segment in v.split('/'):
            configentry.value.append(int(segment.strip()))
        return True
    elif type(configentry.dtype) == enum.EnumMeta:
        configentry.value = configentry.dtype[v]
        return True
    else:
        raise RuntimeError('Cannot reach here')

#Config object generater, based on parsed result