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

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

项目:gitmate-2    作者:GitMateIO    | 项目源码 | 文件源码
def scheduler(cls,
                  interval: (crontab, float),
                  *args,
                  queue: Enum = TaskQueue.SHORT,
                  **kwargs):  # pragma: no cover
        """
        Registers the decorated function as a periodic task. The task should
        not accept any arguments.

        :param interval:    Periodic interval in seconds as float or crontab
                            object specifying task trigger time. See
                            http://docs.celeryproject.org/en/latest/reference/celery.schedules.html#celery.schedules.crontab
        :param queue:       Queue to use for the scheduled task.
        :param args:        Arguments to pass to scheduled task.
        :param kwargs:      Keyword arguments to pass to scheduled task.
        """
        def _wrapper(function: Callable):
            task = celery.task(function,
                               base=ExceptionLoggerTask,
                               queue=queue.value)
            celery.add_periodic_task(interval, task.s(), args, kwargs)
            return function
        return _wrapper
项目:runcommands    作者:wylee    | 项目源码 | 文件源码
def __init__(self, parameter, position, type_=None):
        default = parameter.default
        empty = parameter.empty
        self._parameter = parameter

        self.is_positional = default is empty
        self.is_optional = not self.is_positional
        self.is_keyword_only = self.kind is parameter.KEYWORD_ONLY

        if type_ is not None:
            self.type = type_
            self.is_bool = issubclass(type_, bool)
            self.is_dict = issubclass(type_, dict)
            self.is_enum = issubclass(type_, Enum)
            self.is_list = issubclass(type_, (list, tuple))
        else:
            self.type = str if default in (None, empty) else type(default)
            self.is_bool = isinstance(default, bool)
            self.is_dict = isinstance(default, dict)
            self.is_enum = isinstance(default, Enum)
            self.is_list = isinstance(default, (list, tuple))

        self.position = position
        self.takes_value = self.is_positional or (self.is_optional and not self.is_bool)
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def __getattribute__(self, name):
        # Intercept everything and delegate to the device class by converting
        # names between the D-Bus conventions to Python conventions.
        prop_name = camel_to_snake(name)
        if (prop_name in DeviceAPI._PROPERTIES or prop_name in DeviceAPI._RW_PROPERTIES) \
                and hasattr(self._driver, prop_name):
            value = getattr(self._driver, prop_name)
            if isinstance(value, Enum):
                return value.name.lower()
            if isinstance(value, Color):
                return value.html
            if isinstance(value, (list, tuple)) and len(value) > 0 and isinstance(value[0], Enum):
                return [x.name.lower() for x in value]
            return value

        else:
            return super(DeviceAPI, self).__getattribute__(name)
项目:pyUBoot    作者:molejar    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        """ U-Boot Image Header Constructor
        :param laddr:    Load address
        :param eaddr:    Entry point address
        :param arch:     Architecture (ARCHType Enum)
        :param os:       Operating system (OSType Enum)
        :param image:    Image type (IMGType Enum)
        :param compress: Image compression (COMPRESSType Enum)
        :param name:     Image name (max: 32 chars)
        """
        self.MagicNumber  = 0x27051956  # U-Boot Default Value is 0x27051956
        self.TimeStamp    = int(time.time())
        self.DataSize     = 0
        self.DataCRC      = 0
        self.LoadAddress  = 0 if 'laddr' not in kwargs else kwargs['laddr']
        self.EntryAddress = 0 if 'eaddr' not in kwargs else kwargs['eaddr']
        self.OsType       = OSType.LINUX if 'os' not in kwargs else kwargs['os']
        self.ArchType     = ARCHType.ARM if 'arch' not in kwargs else kwargs['arch']
        self.ImageType    = IMGType.STD if 'image' not in kwargs else kwargs['image']
        self.Compression  = COMPRESSType.NONE if 'compress' not in kwargs else kwargs['compress']
        self.Name         = '' if 'name' not in kwargs else kwargs['name']
项目:korean_restaurant_reservation    作者:JudeLee19    | 项目源码 | 文件源码
def __init__(self):
        self.entities = {
                '<cuisine>' : None,
                '<location>' : None,
                '<party_size>' : None,
                '<rest_type>' : None,
                }
        self.num_features = 4 # tracking 4 entities
        self.rating = None

        # constants
        self.party_sizes = ['??', '??', '??', '?', '??', '?', '??', '???', '??', '???', '??', '??']

        self.locations = ['??', '???', '???', '???', '??', '??', '??', '????', '??', '??', 'LA']

        self.cuisines = ['??','??','???', '????', '??', '??', '??', '??', '??', '???', '??', '???']

        self.rest_types = ['??', '?','??', '??']

        self.EntType = Enum('Entity Type', '<party_size> <location> <cuisine> <rest_type> <non_ent>')
项目:seasnake    作者:pybee    | 项目源码 | 文件源码
def test_without_values(self):
        self.assertGeneratedOutput(
            """
            enum Bar {
                TOP,
                RIGHT,
                BOTTOM,
                LEFT
            };
            """,
            """
            from enum import Enum


            class Bar(Enum):
                TOP = 0
                RIGHT = 1
                BOTTOM = 2
                LEFT = 3
            """
        )
项目:seasnake    作者:pybee    | 项目源码 | 文件源码
def test_values(self):
        self.assertGeneratedOutput(
            """
            enum Bar {
                TOP = 37,
                RIGHT = 42,
                BOTTOM = 55,
                LEFT = 69
            };
            """,
            """
            from enum import Enum


            class Bar(Enum):
                TOP = 37
                RIGHT = 42
                BOTTOM = 55
                LEFT = 69
            """
        )
项目:seasnake    作者:pybee    | 项目源码 | 文件源码
def test_initial_values(self):
        self.assertGeneratedOutput(
            """
            enum Bar {
                TOP = 37,
                RIGHT,
                BOTTOM,
                LEFT
            };
            """,
            """
            from enum import Enum


            class Bar(Enum):
                TOP = 37
                RIGHT = 38
                BOTTOM = 39
                LEFT = 40
            """
        )
项目:seasnake    作者:pybee    | 项目源码 | 文件源码
def test_expressions_for_values(self):
        self.assertGeneratedOutput(
            """
                enum Bar {
                    TOP = 1 << 0,
                    RIGHT = 1 << 1,
                    BOTTOM = 1 << 2,
                    LEFT = 1 << 3
                };
            """,
            """
            from enum import Enum


            class Bar(Enum):
                TOP = 1
                RIGHT = 2
                BOTTOM = 4
                LEFT = 8
            """
        )
项目:seasnake    作者:pybee    | 项目源码 | 文件源码
def test_inner_enum(self):
        self.assertGeneratedOutput(
            """
            class Point {
                enum Temperature {
                    HOT,
                    COLD
                };
            };
            """,
            """
            from enum import Enum


            class Point:
                class Temperature(Enum):
                    HOT = 0
                    COLD = 1
            """
        )
项目:oclubs    作者:SHSIDers    | 项目源码 | 文件源码
def __get_ie(ie):
    if ie is None:
        imp = exp = lambda val: val
    elif ie is NotImplemented:
        imp = exp = lambda val: NotImplemented
    elif isinstance(ie, basestring):
        imp, exp = _object_proxy(ie), lambda val: val.id
    elif isinstance(ie, types.ModuleType):
        imp, exp = ie.loads, ie.dumps
    elif isinstance(ie, type) and issubclass(ie, BaseObject):
        imp, exp = ie, lambda val: val.id
    elif isinstance(ie, type) and issubclass(ie, Enum):
        imp, exp = ie, lambda val: val.value
    elif callable(ie):
        imp = exp = ie

    return imp, exp
项目:oclubs    作者:SHSIDers    | 项目源码 | 文件源码
def __get_search(search, ie):
    if search is False:
        return None
    if search is True:
        if isinstance(ie, tuple):
            ie = ie[1]
        return __get_search(ie, False)
    elif search is None:
        return lambda val: val
    elif isinstance(search, basestring):
        if search == 'User':
            return lambda val: val.passportname
        elif search == 'FormattedText':
            return lambda val: val.raw
        else:
            return lambda val: val.name
    elif isinstance(search, type) and issubclass(search, Enum):
        return lambda val: val.format_name
    elif callable(search):
        return search

    return None
项目:baka    作者:baka-framework    | 项目源码 | 文件源码
def default(self, o):
        # for Enum Type
        if isinstance(o, enum.Enum):
            return o.value

        # for Enum Select Integer
        if isinstance(o, EnumInt):
            return o.key

        if isinstance(o, (datetime, date)):
            return o.isoformat()

        if isinstance(o, Decimal):
            return _number_str(o)

        if isinstance(o, ObjectId):
            return str(o)

        return super(JSONEncoder, self).default(o)
项目:scheduledtask    作者:leonidumanskiy    | 项目源码 | 文件源码
def _datetimeholders_compare(self, a: DateTimeHolder, b: DateTimeHolder, from_fraction: Enum):
        """Partially compare a and b date time holders, starting with fraction.
           For example, if the fraction is DAY, compare only DAY, MONTH and YEAR
        """
        _a = DateTimeHolder()
        _b = DateTimeHolder()
        for fraction_value in range(from_fraction.value, self.highest_fraction.value+1):
            fraction = self.fractions(fraction_value)
            _a[fraction.name] = a[fraction.name]
            _b[fraction.name] = b[fraction.name]
        if _a > _b:
            return 1
        elif _a == _b:
            return 0
        else:
            return -1
项目:flic-hue    作者:richardtguy    | 项目源码 | 文件源码
def _send_command(self, name, items):
        for key, value in items.items():
            if isinstance(value, Enum):
                items[key] = value.value

        if "bd_addr" in items:
            items["bd_addr"] = FlicClient._bdaddr_string_to_bytes(items["bd_addr"])

        opcode = FlicClient._COMMAND_NAME_TO_OPCODE[name]
        data_bytes = FlicClient._COMMAND_STRUCTS[opcode].pack(*FlicClient._COMMAND_NAMED_TUPLES[opcode](**items))
        bytes = bytearray(3)
        bytes[0] = (len(data_bytes) + 1) & 0xff
        bytes[1] = (len(data_bytes) + 1) >> 8
        bytes[2] = opcode
        bytes += data_bytes
        with self._lock:
            if not self._closed:
                self._sock.sendall(bytes)
项目:PokeDuino    作者:tzwenn    | 项目源码 | 文件源码
def setUp(self):

        import enum, ctypes

        class Fruit(enum.Enum):
            Apple, Banana, Citron = range(3)

        class TestStruct(PokeStructure):

            _fields_ = [
                ("_fruit", ctypes.c_uint8),
            ]

            _adapters_ = [
                ("_fruit", Fruit)
            ]

        self.Fruit = Fruit
        self.TestStruct = TestStruct
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def adapt(self, impltype, **kw):
        schema = kw.pop('schema', self.schema)
        metadata = kw.pop('metadata', self.metadata)
        _create_events = kw.pop('_create_events', False)
        if issubclass(impltype, Enum):
            if self.enum_class is not None:
                args = [self.enum_class]
            else:
                args = self.enums
            return impltype(name=self.name,
                            schema=schema,
                            metadata=metadata,
                            convert_unicode=self.convert_unicode,
                            native_enum=self.native_enum,
                            inherit_schema=self.inherit_schema,
                            validate_strings=self.validate_strings,
                            _create_events=_create_events,
                            *args,
                            **kw)
        else:
            # TODO: why would we be here?
            return super(Enum, self).adapt(impltype, **kw)
项目:clickhouse-driver    作者:mymarilyn    | 项目源码 | 文件源码
def before_write_item(self, value):
        source_value = value.name if isinstance(value, Enum) else value
        enum_cls = self.enum_cls

        # Check real enum value
        try:
            if isinstance(source_value, compat.string_types):
                return enum_cls[source_value].value
            else:
                return enum_cls(source_value).value

        except (ValueError, KeyError):
            choices = ', '.join(
                "'{}' = {}".format(x.name, x.value) for x in enum_cls
            )
            enum_str = '{}({})'.format(enum_cls.__name__, choices)

            raise errors.LogicalError(
                "Unknown element '{}' for type {}"
                .format(source_value, enum_str)
            )
项目:clickhouse-driver    作者:mymarilyn    | 项目源码 | 文件源码
def create_enum_column(spec):
    if spec.startswith('Enum8'):
        params = spec[6:-1]
        cls = Enum8Column
    else:
        params = spec[7:-1]
        cls = Enum16Column

    d = {}
    for param in params.split(", '"):
        pos = param.rfind("'")
        name = param[:pos].lstrip("'")
        value = int(param[pos + 1:].lstrip(' ='))
        d[name] = value

    return cls(Enum(cls.ch_type, d))
项目:clickhouse-driver    作者:mymarilyn    | 项目源码 | 文件源码
def escape_param(item):
    if item is None:
        return 'NULL'

    elif isinstance(item, datetime):
        return "'%s'" % item.strftime('%Y-%m-%d %H:%M:%S')

    elif isinstance(item, date):
        return "'%s'" % item.strftime('%Y-%m-%d')

    elif isinstance(item, string_types):
        return "'%s'" % ''.join(escape_chars_map.get(c, c) for c in item)

    elif isinstance(item, (list, tuple)):
        return "[%s]" % ', '.join(text_type(escape_param(x)) for x in item)

    elif isinstance(item, Enum):
        return item.value

    elif isinstance(item, UUID):
        return "'%s'" % str(item)

    else:
        return item
项目:needybot-core    作者:needybot    | 项目源码 | 文件源码
def resolve_topic_name(topic):

    """
    Given a topic of type `enum.Enum`, or of type `str`,
    get the string value of its publisher channel.

    Args:
        topic (enum.Enum | str): the topic to resolve, as
            either an enum.Enum type or a string.

    Returns:
        string: the publisher channel for the topic
        None: if the topic arg is not one of the two acceptable
            types, then None is returned
    """

    if isinstance(topic, enum.Enum):
        return topic.value
    elif isinstance(topic, str):
        return topic
    else:
        return None
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def adapt(self, impltype, **kw):
        schema = kw.pop('schema', self.schema)
        metadata = kw.pop('metadata', self.metadata)
        _create_events = kw.pop('_create_events', False)
        if issubclass(impltype, Enum):
            if self.enum_class is not None:
                args = [self.enum_class]
            else:
                args = self.enums
            return impltype(name=self.name,
                            schema=schema,
                            metadata=metadata,
                            convert_unicode=self.convert_unicode,
                            native_enum=self.native_enum,
                            inherit_schema=self.inherit_schema,
                            validate_strings=self.validate_strings,
                            _create_events=_create_events,
                            *args,
                            **kw)
        else:
            # TODO: why would we be here?
            return super(Enum, self).adapt(impltype, **kw)
项目:gitmate-2    作者:GitMateIO    | 项目源码 | 文件源码
def responder(cls, plugin_name: str, *actions: [Enum],
                  queue: Enum=TaskQueue.SHORT):
        """
        Registers the decorated function as a responder to the actions
        provided. Specifying description as defaults on option specific args
        is mandatory.
        """
        def _wrapper(function):
            task = celery.task(function,
                               base=ExceptionLoggerTask,
                               queue=queue.value)
            for action in actions:
                cls._responders[action].append(task)
            cls._plugins[task] = plugin_name
            params = signature(function).parameters.values()
            cls._options[task] = [param.name for param in params
                                  if param.default is not Parameter.empty]
            return function
        return _wrapper
项目:clubsandwich    作者:irskep    | 项目源码 | 文件源码
def add_subscriber(self, obj, name, entity):
        """
        :param object obj: Object to be called when the event fires
        :param str|Enum name: Name of the event. May be a string-valued enum.
        :param entity: If ``None``, receive all events regardless of their entity.
                       Otherwise, only receive events whose entity ``is`` this
                       object.

        Store ``(obj, entity)`` as a subscriber for the event *name*. When
        :py:meth:`fire` is called with a pattern that matches ``(obj, entity)``,
        call ``obj.on_[name](Event(name, entity, data))``.

        An event is said to "match" a subscription if the subscription has the same
        event name, and either the subscriber's entity is ``None``, or the
        subscriber's entity ``is`` the event's entity.

        You may subscribe more than once to receive the event multiple times.
        """
        if isinstance(name, Enum):
            name = name.value
        self.handlers[name].append((obj, entity))
项目:clubsandwich    作者:irskep    | 项目源码 | 文件源码
def fire(self, name, entity, data):
        """
        :param object obj: Object that is subscribed
        :param str|Enum name: Name of the event. May be a string-valued enum.
        :param entity: Entity, or ``None``.
        :param data: Arbitrary data to add to the :py:class:`Event`.

        Call all event handlers for the given *name* + *entity*, and pass *data*.
        """
        if isinstance(name, Enum):
            name = name.value
        method_name = "on_" + name.lower()
        event = Event(name, entity, data)
        for (obj, required_entity) in self.handlers[name]:
            if required_entity is None or entity is required_entity:
                method = getattr(obj, method_name)
                method(event)
            if event._is_halted or self._is_halted:
                break
        self._is_halted = False
项目:auDeep    作者:auDeep    | 项目源码 | 文件源码
def _format_enum_values(values: List[int],
                        enum_class: Type[Enum]):
    """
    Formats a list of enum values represented by their numeric value, which may contain missing values indicated by 
    None.

    Returns a list containing a string representation for each list element, which is "None" if the element is None, or
    the name of the enum member corresponding to the numeric value in the list otherwise.

    Parameters
    ----------
    values: list
        A list of numeric enum values
    enum_class: Type[Enum]
        The enum type

    Returns
    -------
    list
        A list of strings containing a string representation for each element in the specified list
    """
    return ["None" if x == _MISSING_VALUE_INT else enum_class(x).name for x in values]
项目:ted-editor    作者:tarnheld    | 项目源码 | 文件源码
def __init__(self,canvas):

    self.isOpen    = False
    self.SegType   = Enum("SegType", "Straight Biarc End")
    self.point     = [ coords(0,0) ]
    self.tangent   = [None]
    self.biarc_r   = []
    self.segwidth  = []
    self.segtype   = []

    self.cidmap    = {}

    self.color = "gray"
    self.tag = "segment"
    self.movePoint(0,coords(100,100))
    self.appendPoint(coords(200,110),self.SegType.Straight,None,30)
    #self.appendPoint(coords(320,310),self.SegType.Biarc,30,1)
    self.appendPoint(coords(520,400),self.SegType.Biarc,None,30,1)
    self.insertPoint(2,coords(320,310),self.SegType.Biarc,None,30,1)
    self.insertPoint(2,coords(620,610),self.SegType.Straight,None,30,1)
    self.removePoint(2)
项目:aria    作者:mattmaynes2    | 项目源码 | 文件源码
def json_encode(obj):
        if( isinstance(obj,(Device,DeviceType,Attribute,Parameter))):
            return {key.lstrip('_'): value for key, value in obj.__dict__.items()}
        if(isinstance(obj,Enum)):
            return str(obj.value)
        if( isinstance(obj,bytes)):
            return str(UUID(bytes=obj))
        if( isinstance(obj,UUID)):
            return str(obj)
        if (isinstance(obj, type(threading.Lock()))):
            return str(obj)
        if (isinstance(obj, threading.Condition)):
            return str(obj)
        if (isinstance(obj, threading.Thread)):
            return str(obj)
        else:
            return
项目:azure-cli    作者:Azure    | 项目源码 | 文件源码
def todict(obj):  # pylint: disable=too-many-return-statements

    if isinstance(obj, dict):
        return {k: todict(v) for (k, v) in obj.items()}
    elif isinstance(obj, list):
        return [todict(a) for a in obj]
    elif isinstance(obj, Enum):
        return obj.value
    elif isinstance(obj, (date, time, datetime)):
        return obj.isoformat()
    elif isinstance(obj, timedelta):
        return str(obj)
    elif hasattr(obj, '_asdict'):
        return todict(obj._asdict())
    elif hasattr(obj, '__dict__'):
        return dict([(to_camel_case(k), todict(v))
                     for k, v in obj.__dict__.items()
                     if not callable(v) and not k.startswith('_')])
    return obj
项目:asyncpgsa    作者:CanopyTax    | 项目源码 | 文件源码
def test_querying_table(metadata):
    """
    Create an object for test table.

    """

    # When using pytest-xdist, we don't want concurrent table creations
    # across test processes so we assign a unique name for table based on
    # the current worker id.
    worker_id = os.environ.get('PYTEST_XDIST_WORKER', 'master')
    return Table(
        'test_querying_table_' + worker_id, metadata,
        Column('id', types.Integer, autoincrement=True, primary_key=True),
        Column('t_string', types.String(60)),
        Column('t_list', types.ARRAY(types.String(60))),
        Column('t_enum', types.Enum(MyEnum)),
        Column('t_int_enum', types.Enum(MyIntEnum)),
        Column('t_datetime', types.DateTime()),
        Column('t_date', types.DateTime()),
        Column('t_interval', types.Interval()),
        Column('uniq_uuid', PG_UUID, nullable=False, unique=True, default=uuid4),
    )
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
def test_enum_local_var_assign(converter):
    class EnumType(Enum):
        ENUMVALUE = 0

    code = textwrap.dedent("""\
        def f():
            a = EnumType.ENUMVALUE""")

    datamodel = DataModel(locals={'f': {'a': EnumType.ENUMVALUE}},
                          self_data={})

    expect = textwrap.dedent("""\

        procedure f is
            variable a: EnumType;
        begin
            a := ENUMVALUE;
        end procedure;""")
    conv = converter(code, datamodel)
    assert expect == str(conv)
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
def test_enum_self_var_assign(converter):
    class EnumType(Enum):
        ENUMVALUE = 0

    code = textwrap.dedent("""\
        def f():
            self.a = EnumType.ENUMVALUE""")

    datamodel = DataModel(locals={},
                          self_data={'a': EnumType.ENUMVALUE})

    expect = textwrap.dedent("""\

        procedure f is

        begin
            self.a := ENUMVALUE;
        end procedure;""")
    conv = converter(code, datamodel)
    assert expect == str(conv)
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
def test_enum_in_if(converter):
    class EnumType(Enum):
        ENUMVALUE = 0

    code = textwrap.dedent("""\
        def f():
            if a == EnumType.ENUMVALUE:
                b""")

    datamodel = DataModel(locals={'f': {'c': EnumType.ENUMVALUE}},
                          self_data={})

    expect = textwrap.dedent("""\

        procedure f is

        begin
            if a = ENUMVALUE then
                b
            end if;
        end procedure;""")
    conv = converter(code, datamodel)
    assert expect == str(conv)
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
def normal_to_slv(self, var, var_name) -> str:
        if type(var) == int:
            return f'std_logic_vector(to_signed({var_name}, 32))'
        elif type(var) == bool:
            return f'bool_to_logic({var_name})'
        elif type(var) == Sfix:
            return f'to_slv({var_name})'
        elif type(var) == ComplexSfix:
            return f'to_slv({var_name}.real) & to_slv({var_name}.imag)'
        elif isinstance(var, Enum):
            return self.normal_to_slv(var.value, var_name)
        elif isinstance(var, list):
            if isinstance(var[0], bool):
                return f'bool_list_to_logic({var_name})'
        else:
            assert 0
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
def is_convertible(obj):
    allowed_types = [ComplexSfix, Sfix, int, bool, Const]
    if type(obj) in allowed_types:
        return True
    elif isinstance(obj, list):
        # To check whether all elements are of the same type
        if len(set(map(type, obj))) == 1:
            if all(type(x) in allowed_types for x in obj):
                return True
            elif isinstance(obj[0], HW):  # list of submodules
                return True
    elif isinstance(obj, Enum):
        return True
    elif isinstance(obj, HW):
        return True

    return False
项目:webapp    作者:superchilli    | 项目源码 | 文件源码
def adapt(self, impltype, **kw):
        schema = kw.pop('schema', self.schema)
        metadata = kw.pop('metadata', self.metadata)
        _create_events = kw.pop('_create_events', False)
        if issubclass(impltype, Enum):
            if self.enum_class is not None:
                args = [self.enum_class]
            else:
                args = self.enums
            return impltype(name=self.name,
                            schema=schema,
                            metadata=metadata,
                            convert_unicode=self.convert_unicode,
                            native_enum=self.native_enum,
                            inherit_schema=self.inherit_schema,
                            validate_strings=self.validate_strings,
                            _create_events=_create_events,
                            *args,
                            **kw)
        else:
            # TODO: why would we be here?
            return super(Enum, self).adapt(impltype, **kw)
项目:nlp    作者:Shmuma    | 项目源码 | 文件源码
def encode_tags(tags, output):
    result = []

    for tag in tags:
        t_set = set(tag.split(' '))
        assert issubclass(output, enum.Enum)
        res_index = None
        for idx, member in enumerate(output.__members__.values()):
            if member.value == '' or member.value in t_set:
                res_index = idx
        assert res_index is not None
        v = np.zeros(len(output), dtype=np.float32)
        v[res_index] = 1.0
        result.append(v)

    return result
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_attribute_deletion(self):
        class Season(Enum):
            SPRING = 1
            SUMMER = 2
            AUTUMN = 3
            WINTER = 4

            def spam(cls):
                pass

        self.assertTrue(hasattr(Season, 'spam'))
        del Season.spam
        self.assertFalse(hasattr(Season, 'spam'))

        with self.assertRaises(AttributeError):
            del Season.SPRING
        with self.assertRaises(AttributeError):
            del Season.DRY
        with self.assertRaises(AttributeError):
            del Season.SPRING.name
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_invalid_names(self):
        with self.assertRaises(ValueError):
            class Wrong(Enum):
                mro = 9
        with self.assertRaises(ValueError):
            class Wrong(Enum):
                _create_= 11
        with self.assertRaises(ValueError):
            class Wrong(Enum):
                _get_mixins_ = 9
        with self.assertRaises(ValueError):
            class Wrong(Enum):
                _find_new_ = 1
        with self.assertRaises(ValueError):
            class Wrong(Enum):
                _any_name_ = 9
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_comparisons(self):
        Season = self.Season
        with self.assertRaises(TypeError):
            Season.SPRING < Season.WINTER
        with self.assertRaises(TypeError):
            Season.SPRING > 4

        self.assertNotEqual(Season.SPRING, 1)

        class Part(Enum):
            SPRING = 1
            CLIP = 2
            BARREL = 3

        self.assertNotEqual(Season.SPRING, Part.SPRING)
        with self.assertRaises(TypeError):
            Season.SPRING < Part.CLIP
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_enum_duplicates(self):
        class Season(Enum):
            SPRING = 1
            SUMMER = 2
            AUTUMN = FALL = 3
            WINTER = 4
            ANOTHER_SPRING = 1
        lst = list(Season)
        self.assertEqual(
            lst,
            [Season.SPRING, Season.SUMMER,
             Season.AUTUMN, Season.WINTER,
            ])
        self.assertIs(Season.FALL, Season.AUTUMN)
        self.assertEqual(Season.FALL.value, 3)
        self.assertEqual(Season.AUTUMN.value, 3)
        self.assertIs(Season(3), Season.AUTUMN)
        self.assertIs(Season(1), Season.SPRING)
        self.assertEqual(Season.FALL.name, 'AUTUMN')
        self.assertEqual(
                [k for k,v in Season.__members__.items() if v.name != k],
                ['FALL', 'ANOTHER_SPRING'],
                )
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_programatic_function_string(self):
        SummerMonth = Enum('SummerMonth', 'june july august')
        lst = list(SummerMonth)
        self.assertEqual(len(lst), len(SummerMonth))
        self.assertEqual(len(SummerMonth), 3, SummerMonth)
        self.assertEqual(
                [SummerMonth.june, SummerMonth.july, SummerMonth.august],
                lst,
                )
        for i, month in enumerate('june july august'.split(), 1):
            e = SummerMonth(i)
            self.assertEqual(int(e.value), i)
            self.assertNotEqual(e, i)
            self.assertEqual(e.name, month)
            self.assertIn(e, SummerMonth)
            self.assertIs(type(e), SummerMonth)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_programatic_function_string_list(self):
        SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
        lst = list(SummerMonth)
        self.assertEqual(len(lst), len(SummerMonth))
        self.assertEqual(len(SummerMonth), 3, SummerMonth)
        self.assertEqual(
                [SummerMonth.june, SummerMonth.july, SummerMonth.august],
                lst,
                )
        for i, month in enumerate('june july august'.split(), 1):
            e = SummerMonth(i)
            self.assertEqual(int(e.value), i)
            self.assertNotEqual(e, i)
            self.assertEqual(e.name, month)
            self.assertIn(e, SummerMonth)
            self.assertIs(type(e), SummerMonth)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_programatic_function_iterable(self):
        SummerMonth = Enum(
                'SummerMonth',
                (('june', 1), ('july', 2), ('august', 3))
                )
        lst = list(SummerMonth)
        self.assertEqual(len(lst), len(SummerMonth))
        self.assertEqual(len(SummerMonth), 3, SummerMonth)
        self.assertEqual(
                [SummerMonth.june, SummerMonth.july, SummerMonth.august],
                lst,
                )
        for i, month in enumerate('june july august'.split(), 1):
            e = SummerMonth(i)
            self.assertEqual(int(e.value), i)
            self.assertNotEqual(e, i)
            self.assertEqual(e.name, month)
            self.assertIn(e, SummerMonth)
            self.assertIs(type(e), SummerMonth)
项目:datapipelines-python    作者:meraki-analytics    | 项目源码 | 文件源码
def evaluate(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> True:
        try:
            value = query[self.key]
            for type in self.types:
                if issubclass(type, Enum) and isinstance(value, str):
                    value = type(value)
                if isinstance(value, type):
                    query[self.key] = value
                    return True
            raise WrongValueTypeError("{key} must be of type {type} in query!".format(key=self.key, type=self))
        except KeyError:
            if self.child:
                self.child.evaluate(query, context)
        return True
项目:aws-encryption-sdk-cli    作者:awslabs    | 项目源码 | 文件源码
def json_ready_header(header):
    # type: (MessageHeader) -> Dict[str, Any]
    """Create a JSON-serializable representation of a :class:`aws_encryption_sdk.structures.MessageHeader`.

    http://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure

    :param header: header for which to create a JSON-serializable representation
    :type header: aws_encryption_sdk.structures.MessageHeader
    :rtype: dict
    """
    dict_header = attr.asdict(header)

    del dict_header['content_aad_length']
    dict_header['version'] = str(float(dict_header['version'].value))
    dict_header['algorithm'] = dict_header['algorithm'].name

    for key, value in dict_header.items():
        if isinstance(value, Enum):
            dict_header[key] = value.value

    dict_header['message_id'] = unicode_b64_encode(dict_header['message_id'])

    dict_header['encrypted_data_keys'] = sorted(
        list(dict_header['encrypted_data_keys']),
        key=lambda x: six.b(x['key_provider']['provider_id']) + x['key_provider']['key_info']
    )
    for data_key in dict_header['encrypted_data_keys']:
        data_key['key_provider']['provider_id'] = unicode_b64_encode(six.b(data_key['key_provider']['provider_id']))
        data_key['key_provider']['key_info'] = unicode_b64_encode(data_key['key_provider']['key_info'])
        data_key['encrypted_data_key'] = unicode_b64_encode(data_key['encrypted_data_key'])

    return dict_header
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def set_effect(self, effect: Enum, *args) -> bool:
        if self._driver.has_quirk(Quirks.EXTENDED_FX_CMDS):
            if effect.name in ExtendedFX.__members__:
                return self._set_effect_extended(ExtendedFX[effect.name], *args)
            return False
        return self._set_effect_basic(effect, *args)
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def trait_as_dict(trait: TraitType) -> dict:
    """
    Convert a trait to a dict for sending over D-Bus or the like

    :param trait: the trait to be converted
    :return: dict representing this trait
    """
    cls = trait.__class__
    tdict = {}

    for k, v in vars(trait).items():
        if k.startswith('__') or k == 'this_class':
            continue
        if hasattr(cls, k) and getattr(cls, k) == v:
            continue
        if isinstance(v, Iterable) and len(v) == 0:
            continue

        if k.startswith('_'):
            tdict[k[1:]] = v
        else:
            tdict[k] = v

    if isinstance(trait, UseEnum):
        cls = CaselessStrEnum
        tdict['values'] = tuple(trait.enum_class.__members__.keys())
        if 'enum_class' in tdict:
            del tdict['enum_class']

    for k, v in tdict.items():
        if isinstance(v, TraitType):
            tdict[k] = trait_as_dict(v)
        if isinstance(v, enum.Enum):
            tdict[k] = v.name
        if isinstance(v, type):
            tdict[k] = '%s.%s' % (v.__module__, v.__name__)

    tdict['__class__'] = (cls.__module__, cls.__name__)
    return tdict
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def add_traits_to_argparse(obj: HasTraits, parser: ArgumentParser,
                           prefix: str=None):
    """
    Add all traits from the given object to the argparse context.

    :param obj: an instance of HasTraits
    :param parser: argparse parser
    :param prefix: string to prefix keys with
    """
    for key, trait in obj.traits().items():
        if trait.get_metadata('config') is not True:
            continue

        argname = '--%s' % key
        if prefix is not None:
            argname = '--%s.%s' % (prefix, key)

        if isinstance(trait, Container):
            parser.add_argument(argname, nargs='+', help=trait.info_text)
        elif isinstance(trait, Enum):
            parser.add_argument(argname, type=str.lower,
                                choices=[x.lower() for x in trait.values],
                                help=trait.info_text)
        else:
            argtype = str
            if hasattr(trait, 'default_value'):
                argtype = type(trait.default_value)
            parser.add_argument(argname, type=argtype, help=trait.info_text)
项目:pyUBoot    作者:molejar    | 项目源码 | 文件源码
def CRC32(data):
    """ Help function for 32bit CRC calculation
    :param data: Tha data blob as byte array
    :return: CRC Value
    """
    return zlib.crc32(data) & 0xFFFFFFFF
# ----------------------------------------------------------------------------------------------------------------------


# ----------------------------------------------------------------------------------------------------------------------
# Customized Enum Class
# ----------------------------------------------------------------------------------------------------------------------