Python enum.Enum() Examples

The following are 30 code examples of enum.Enum(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module enum , or try the search function .
Example #1
Source File: patches.py    From django-more with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
                db_type=db_type,
                values=values),
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example #2
Source File: utils.py    From fastapi with MIT License 7 votes vote down vote up
def get_openapi_operation_request_body(
    *,
    body_field: Optional[ModelField],
    model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> Optional[Dict]:
    if not body_field:
        return None
    assert isinstance(body_field, ModelField)
    # ignore mypy error until enum schemas are released
    body_schema, _, _ = field_schema(
        body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX  # type: ignore
    )
    field_info = cast(Body, get_field_info(body_field))
    request_media_type = field_info.media_type
    required = body_field.required
    request_body_oai: Dict[str, Any] = {}
    if required:
        request_body_oai["required"] = required
    request_body_oai["content"] = {request_media_type: {"schema": body_schema}}
    return request_body_oai 
Example #3
Source File: utils.py    From fastapi with MIT License 7 votes vote down vote up
def get_openapi_operation_parameters(
    *,
    all_route_params: Sequence[ModelField],
    model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> List[Dict[str, Any]]:
    parameters = []
    for param in all_route_params:
        field_info = get_field_info(param)
        field_info = cast(Param, field_info)
        # ignore mypy error until enum schemas are released
        parameter = {
            "name": param.alias,
            "in": field_info.in_.value,
            "required": param.required,
            "schema": field_schema(
                param, model_name_map=model_name_map, ref_prefix=REF_PREFIX  # type: ignore
            )[0],
        }
        if field_info.description:
            parameter["description"] = field_info.description
        if field_info.deprecated:
            parameter["deprecated"] = field_info.deprecated
        parameters.append(parameter)
    return parameters 
Example #4
Source File: createminidump.py    From minidump with MIT License 6 votes vote down vote up
def enum_process_names():
	pid_to_name = {}
	
	for pid in enum_pids():
		pid_to_name[pid] = 'Not found'
		process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
		if process_handle is None:
			logging.debug('[Enum Processes]Failed to open process PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		image_name = (ctypes.c_char*MAX_PATH)()
		max_path = DWORD(4096)
		#res = GetProcessImageFileName(process_handle, image_name, MAX_PATH)
		res = QueryFullProcessImageName(process_handle, 0 ,image_name, ctypes.byref(max_path))
		if res == 0:
			logging.debug('[Enum Proceses]Failed GetProcessImageFileName on PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		pid_to_name[pid] = image_name.value.decode()
	return pid_to_name 
Example #5
Source File: fields.py    From django-more with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_python(self, value):
        if value is None or isinstance(value, self.type_def):
            return value
        if isinstance(value, Enum):
            # Enum member of the wrong type!
            raise ValidationError("Invalid enum '{}' is a member of an incompatible enumeration".format(repr(value)))
        if isinstance(value, str):
            with suppress(ValueError):
                return self.type_def(str(value))
            # Enum match failed, if not case_sensitive, try insensitive scan
            if self.case_sensitive is False:
                for em in self.type_def:
                    if str(value).lower() == em.value.lower():
                        return em
            # Check for a Enum member string representation
            if value.startswith(self.type_def.__name__ + '.'):
                with suppress(ValueError):
                    return self.type_def[value[len(self.type_def.__name__) + 1:]]
            raise ValidationError("Invalid value '{}' not in enumeration {}".format(
                value, [em.value for em in self.type_def]))
        raise ValidationError("Invalid type '{}' is not an enum member or string".format(type(value).__name__)) 
Example #6
Source File: util.py    From knack with MIT License 6 votes vote down vote up
def todict(obj, post_processor=None):  # pylint: disable=too-many-return-statements
    """
    Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
    dictionary in the process
    """
    if isinstance(obj, dict):
        result = {k: todict(v, post_processor) for (k, v) in obj.items()}
        return post_processor(obj, result) if post_processor else result
    if isinstance(obj, list):
        return [todict(a, post_processor) for a in obj]
    if isinstance(obj, Enum):
        return obj.value
    if isinstance(obj, (date, time, datetime)):
        return obj.isoformat()
    if isinstance(obj, timedelta):
        return str(obj)
    if hasattr(obj, '_asdict'):
        return todict(obj._asdict(), post_processor)
    if hasattr(obj, '__dict__'):
        result = {to_camel_case(k): todict(v, post_processor)
                  for k, v in obj.__dict__.items()
                  if not callable(v) and not k.startswith('_')}
        return post_processor(obj, result) if post_processor else result
    return obj 
Example #7
Source File: test_argparser.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_type_conv_invalid(typ, value, multi):
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        msg = 'foo: Invalid value {}'.format(value)
    elif typ is Enum:
        msg = ('foo: Invalid value {} - expected one of: foo, '
               'foo-bar'.format(value))
    else:
        msg = 'foo: Invalid {} value {}'.format(typ.__name__, value)

    with pytest.raises(cmdexc.ArgumentTypeError, match=msg):
        if multi:
            argparser.multitype_conv(param, [typ], value)
        else:
            argparser.type_conv(param, typ, value) 
Example #8
Source File: __init__.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def render(
    obj: typing.Union[typing.Type[enum.Enum], typing.Type[messages.Struct]]
) -> str:
    if issubclass(obj, messages.Struct):
        return obj.render()
    else:
        assert issubclass(obj, enum.Enum)

        buf = render_utils.RenderBuffer()
        buf.write(f'enum {obj.__name__} {{')
        with buf.indent():
            for membername, member in obj.__members__.items():
                buf.write(
                    f'{membername.ljust(messages._PAD - 1)} = '
                    f'{member.value:#x};'
                )
        buf.write('};')
        return str(buf) 
Example #9
Source File: endpoint.py    From yui with GNU Affero General Public License v3.0 6 votes vote down vote up
def prepare_for_json(obj):
    if isinstance(obj, (list, tuple, set)):
        return [prepare_for_json(x) for x in obj]
    elif issubclass(obj.__class__, enum.Enum):
        return obj.value
    elif isinstance(obj, dict):
        return {
            prepare_for_json(k): prepare_for_json(v)
            for k, v in obj.items()
            if v is not None
            and ((isinstance(v, list) and v) or not isinstance(v, list))
        }
    elif isinstance(obj, str):
        return obj
    try:
        return prepare_for_json(attr.asdict(obj))
    except attr.exceptions.NotAnAttrsClassError:
        pass
    return obj 
Example #10
Source File: experiment.py    From garage with MIT License 6 votes vote down vote up
def default(self, o):
        """Perform JSON encoding.

        Args:
            o (object): Object to encode.

        Returns:
            str: Object encoded in JSON.

        """
        # Why is this method hidden? What does that mean?
        # pylint: disable=method-hidden

        if isinstance(o, type):
            return {'$class': o.__module__ + '.' + o.__name__}
        elif isinstance(o, enum.Enum):
            return {
                '$enum':
                o.__module__ + '.' + o.__class__.__name__ + '.' + o.name
            }
        elif callable(o):
            return {'$function': o.__module__ + '.' + o.__name__}
        return json.JSONEncoder.default(self, o) 
Example #11
Source File: tests.py    From casepro with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_json_encode(self):
        class MyEnum(Enum):
            bar = 1

        class MyClass(object):
            def to_json(self):
                return dict(bar="X")

        data = [
            "string",
            datetime(2015, 10, 9, 14, 48, 30, 123456, tzinfo=pytz.utc).astimezone(pytz.timezone("Africa/Kigali")),
            MyEnum.bar,
            MyClass(),
        ]

        self.assertEqual(json_encode(data), '["string", "2015-10-09T14:48:30.123456Z", "bar", {"bar": "X"}]')
        self.assertEqual(json_encode({"foo": "bar\u1234"}), '{"foo": "bar\\u1234"}') 
Example #12
Source File: _ir_to_string.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def ir_to_string(ir_elem, line_indent=''):
    next_line_indent = line_indent + '  '

    if ir_elem is None:
        return 'None'
    elif isinstance(ir_elem, (str, bool, int, Enum)):
        return repr(ir_elem)
    elif isinstance(ir_elem, (list, tuple, set, frozenset)):
        return ('['
                + ','.join('\n' + next_line_indent + ir_to_string(child_node, next_line_indent)
                           for child_node in ir_elem)
                + ']')
    else:
        return (ir_elem.__class__.__name__
                + '('
                + ','.join('\n' + next_line_indent + field_name + ' = ' + ir_to_string(child_node, next_line_indent)
                           for field_name, child_node in ir_elem.__dict__.items())
                + ')') 
Example #13
Source File: utils_gdb.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def send_signal(self, signal_name):
        """
        Send a signal to the inferior.

        :param signal_name: Signal name as a string or integer
        """
        if isinstance(signal_name, str):
            signal_name = getattr(signal, signal_name)

        if isinstance(signal_name, Enum):
            signal_name = signal_name.value

        if isinstance(signal_name, int):
            os.kill(self.pid, signal_name)
        else:
            raise ValueError("Signal should be a string or an integer.") 
Example #14
Source File: GPUmodule.py    From gpu-utils with GNU General Public License v3.0 6 votes vote down vote up
def num_gpus(self, vendor: Enum = GpuItem.GPU_Vendor.ALL) -> Dict[str, int]:
        """
        Return the count of GPUs by total, rw, r-only or w-only.

        :param vendor: Only count vendor GPUs of specific vendor or all vendors by default.
        :return: Dictionary of GPU counts
        """
        try:
            vendor_name = vendor.name
        except AttributeError:
            raise AttributeError('Error: {} not a valid vendor name: [{}]'.format(vendor, GpuItem.GPU_Vendor))
        results_dict = {'vendor': vendor_name, 'total': 0, 'rw': 0, 'r-only': 0, 'w-only': 0}
        for gpu in self.gpus():
            if vendor != GpuItem.GPU_Vendor.ALL:
                if vendor != gpu.prm.vendor:
                    continue
            if gpu.prm.readable and gpu.prm.writable:
                results_dict['rw'] += 1
            elif gpu.prm.readable:
                results_dict['r-only'] += 1
            elif gpu.prm.writable:
                results_dict['w-only'] += 1
            results_dict['total'] += 1
        return results_dict 
Example #15
Source File: functions.py    From related with MIT License 6 votes vote down vote up
def to_model(cls, value):
    """
    Coerce a value into a model object based on a class-type (cls).
    :param cls: class type to coerce into
    :param value: value to be coerced
    :return: original value or coerced value (value')
    """

    if isinstance(value, cls) or value is None:
        pass  # skip if right type or value is None

    elif issubclass(cls, Enum):
        value = cls(value)

    elif is_model(cls) and isinstance(value, dict):
        value = convert_key_to_attr_names(cls, value)
        value = cls(**value)

    else:
        value = cls(value)

    return value 
Example #16
Source File: alchemy_json_encoder.py    From AppServer with MIT License 6 votes vote down vote up
def decode(obj):
        if obj and isinstance(obj.__class__, DeclarativeMeta):
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and not x.endswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                if isinstance(data, datetime.datetime):
                    fields[field] = data.timestamp()
                elif isinstance(data, datetime.date):
                    fields[field] = data.isoformat()
                elif isinstance(data, datetime.timedelta):
                    fields[field] = (datetime.datetime.min + data).time().isoformat()
                elif isinstance(data, int) or isinstance(data, float) or isinstance(data, str):
                    fields[field] = data
                elif isinstance(data, enum.Enum):
                    fields[field] = data.value
                elif isinstance(data.__class__, DeclarativeMeta):
                    fields[field] = AlchemyEncoder.decode(data)
                elif isinstance(data, list):
                    fields[field] = [AlchemyEncoder.decode(d) for d in data]
            return fields
        else:
            return obj 
Example #17
Source File: cloudpickle.py    From pywren-ibm-cloud with Apache License 2.0 6 votes vote down vote up
def _save_dynamic_enum(self, obj, clsdict):
        """Special handling for dynamic Enum subclasses

        Use a dedicated Enum constructor (inspired by EnumMeta.__call__) as the
        EnumMeta metaclass has complex initialization that makes the Enum
        subclasses hold references to their own instances.
        """
        members = dict((e.name, e.value) for e in obj)

        # Python 2.7 with enum34 can have no qualname:
        qualname = getattr(obj, "__qualname__", None)

        self.save_reduce(_make_skeleton_enum,
                         (obj.__bases__, obj.__name__, qualname, members,
                          obj.__module__, _ensure_tracking(obj), None),
                         obj=obj)

        # Cleanup the clsdict that will be passed to _rehydrate_skeleton_class:
        # Those attributes are already handled by the metaclass.
        for attrname in ["_generate_next_value_", "_member_names_",
                         "_member_map_", "_member_type_",
                         "_value2member_map_"]:
            clsdict.pop(attrname, None)
        for member in members:
            clsdict.pop(member) 
Example #18
Source File: terms.py    From pypika with Apache License 2.0 6 votes vote down vote up
def get_value_sql(self, **kwargs: Any) -> str:
        quote_char = kwargs.get("secondary_quote_char") or ""

        # FIXME escape values
        if isinstance(self.value, Term):
            return self.value.get_sql(**kwargs)
        if isinstance(self.value, Enum):
            return self.value.value
        if isinstance(self.value, date):
            value = self.value.isoformat()
            return format_quotes(value, quote_char)
        if isinstance(self.value, str):
            value = self.value.replace(quote_char, quote_char * 2)
            return format_quotes(value, quote_char)
        if isinstance(self.value, bool):
            return str.lower(str(self.value))
        if self.value is None:
            return "null"
        return str(self.value) 
Example #19
Source File: GPUmodule.py    From gpu-utils with GNU General Public License v3.0 5 votes vote down vote up
def read_gpu_sensor_set(self, data_type: Enum = SensorSet.All) -> bool:
        """
        Read GPU sensor data from HWMON and DEVICE sensors using the sensor set defined
        by data_type.

        :param data_type: Specifies the sensor set: Dynamic, Static, Info, State, All Monitor
        """
        if self.prm.vendor == self.GPU_Vendor.AMD:
            return self.read_gpu_sensor_set_amd(data_type)
        if self.prm.vendor == self.GPU_Vendor.NVIDIA:
            return self.read_gpu_sensor_set_nv(data_type)
        return False 
Example #20
Source File: fields.py    From django-more with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def value_to_string(self, obj):
        """ Serialise to text value as represented in the Enum member or database """
        value = self.value_from_object(obj)
        return self.get_prep_value(value) 
Example #21
Source File: GPUmodule.py    From gpu-utils with GNU General Public License v3.0 5 votes vote down vote up
def read_gpu_sensor_set_amd(self, data_type: Enum = SensorSet.All) -> bool:
        """
        Read GPU sensor data from HWMON and DEVICE sensors using the sensor set defined
        by data_type.

        :param data_type: Specifies the sensor set: Dynamic, Static, Info, State, All Monitor
        """
        if not self.prm.readable:
            return False

        return_status = False
        param_list = self.sensor_sets[data_type]

        for sensor_type, param_names in param_list.items():
            for param in param_names:
                LOGGER.debug('Processing parameter: %s', param)
                rdata = self.read_gpu_sensor(param, vendor=self.prm.vendor, sensor_type=sensor_type)
                if rdata is False:
                    if param != 'unique_id':
                        LOGGER.debug('Error reading parameter: %s disabling for %s', param, self.prm.card_num)
                        print('Warning: Error reading parameter: {}, disabling for this GPU: {}'.format(param,
                              self.prm.card_num))
                elif rdata is None:
                    LOGGER.debug('Read data [%s], Invalid or disabled parameter: %s', rdata, param)
                else:
                    LOGGER.debug('Valid data [%s] for parameter: %s', rdata, param)
                    self.set_params_value(param, rdata)
                    return_status = True
        return return_status 
Example #22
Source File: GPUmodule.py    From gpu-utils with GNU General Public License v3.0 5 votes vote down vote up
def num_vendor_gpus(self, compatibility: Enum = GpuItem.GPU_Comp.ALL) -> Dict[str, int]:
        """
        Return the count of GPUs by vendor.  Counts total by default, but can also by rw, ronly, or wonly.

        :param compatibility: Only count vendor GPUs if True.
        :return: Dictionary of GPU counts
        """
        try:
            _ = compatibility.name
        except AttributeError:
            raise AttributeError('Error: {} not a valid compatibility name: [{}]'.format(
                                 compatibility, GpuItem.GPU_Comp))
        results_dict = {}
        for gpu in self.gpus():
            if compatibility == GpuItem.GPU_Comp.ReadWrite:
                if not gpu.prm.readable or not gpu.prm.writable:
                    continue
            if compatibility == GpuItem.GPU_Comp.ReadOnly:
                if not gpu.prm.readable:
                    continue
            if compatibility == GpuItem.GPU_Comp.WriteOnly:
                if not gpu.prm.writable:
                    continue
            if gpu.prm.vendor.name not in results_dict.keys():
                results_dict.update({gpu.prm.vendor.name: 1})
            else:
                results_dict[gpu.prm.vendor.name] += 1
        return results_dict 
Example #23
Source File: MainWindow.py    From PyEngine3D with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def select_attribute(self, event):
        for item_id in self.attribute_treeview.selection():
            item_info = self.attribute_treeview.item_infos[item_id]
            if bool == item_info.dataType or numpy.bool == item_info.dataType:
                self.attribute_treeview.inplace_checkbutton('#1', item_id)
            elif type(item_info.dataType) == type(Enum):
                dataType = item_info.dataType
                values = [dataType(i).name for i in range(len(dataType))]
                self.attribute_treeview.inplace_combobox('#1', item_id, values, readonly=False)
            else:
                self.attribute_treeview.inplace_entry('#1', item_id) 
Example #24
Source File: fields.py    From django-more with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def enum_meta(meta):
    """ Turn the meta class into a simplistic descriptor.
        This prevents the Meta class from being picked up as a member of the Enum
    """
    meta.__get__ = lambda: self  # noqa self being undeclared is fine
    return meta 
Example #25
Source File: jsonpickle_util.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
def setUpJsonpickle():
    register(Enum, EnumHandler, base=True) 
Example #26
Source File: transform_test.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_enum_getitem():
    """Test enum_getitem helper."""

    class A(enum.Enum):
        a = 1
        b = 2
        c = 3

    assert enum_getitem(A)('a') == A.a

    with pytest.raises(ValueError):
        enum_getitem(A)('zzz')

    assert enum_getitem(A, fallback='b')('a') == A.a
    assert enum_getitem(A, fallback='b')('zzz') == A.b 
Example #27
Source File: encoder.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def encode(obj):
    if isinstance(obj, (list, tuple, set)):
        return [encode(x) for x in obj]
    elif issubclass(obj.__class__, enum.Enum):
        return obj.value
    elif isinstance(obj, dict):
        return {encode(k): encode(v) for k, v in obj.items() if v is not None}
    elif isinstance(obj, bool):
        return bool2str(obj)
    try:
        return encode(attr.asdict(obj))
    except attr.exceptions.NotAnAttrsClassError:
        pass
    return obj 
Example #28
Source File: constants.py    From tdameritrade with Apache License 2.0 5 votes vote down vote up
def list(cls):
        """Lists all values in Enum

        Found here: https://stackoverflow.com/questions/29503339/how-to-get-all-values-from-python-enum-class/54919285#54919285
        """
        return list(map(lambda c: c.value, cls)) 
Example #29
Source File: gltf2loader.py    From gltf2usd with MIT License 5 votes vote down vote up
def PrimitiveMode(Enum):
    POINTS = 0
    LINES = 1
    LINE_LOOP = 2
    LINE_STRIP = 3
    TRIANGLES = 4
    TRIANGLE_STRIP = 5
    TRIANGLE_FAN = 6 
Example #30
Source File: utils.py    From fastapi with MIT License 5 votes vote down vote up
def get_model_definitions(
    *,
    flat_models: Set[Union[Type[BaseModel], Type[Enum]]],
    model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> Dict[str, Any]:
    definitions: Dict[str, Dict] = {}
    for model in flat_models:
        # ignore mypy error until enum schemas are released
        m_schema, m_definitions, m_nested_models = model_process_schema(
            model, model_name_map=model_name_map, ref_prefix=REF_PREFIX  # type: ignore
        )
        definitions.update(m_definitions)
        model_name = model_name_map[model]
        definitions[model_name] = m_schema
    return definitions