Python enum.Enum() Examples

The following are 30 code examples for showing how to use enum.Enum(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module enum , or try the search function .

Example 1
Project: pypika   Author: kayak   File: terms.py    License: 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 2
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    License: 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 3
Project: AppServer   Author: skytoup   File: alchemy_json_encoder.py    License: 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 4
Project: qutebrowser   Author: qutebrowser   File: test_argparser.py    License: 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 5
Project: minidump   Author: skelsec   File: createminidump.py    License: 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 6
Project: knack   Author: microsoft   File: util.py    License: 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
Project: tmppy   Author: google   File: _ir_to_string.py    License: 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 8
Project: fastapi   Author: tiangolo   File: utils.py    License: MIT License 6 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 9
Project: fastapi   Author: tiangolo   File: utils.py    License: MIT License 6 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 10
Project: avocado-vt   Author: avocado-framework   File: utils_gdb.py    License: 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 11
Project: yui   Author: item4   File: endpoint.py    License: 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 12
Project: garage   Author: rlworkgroup   File: experiment.py    License: 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 13
Project: django-more   Author: ashleywaite   File: patches.py    License: BSD 3-Clause "New" or "Revised" License 6 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 14
Project: django-more   Author: ashleywaite   File: fields.py    License: 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 15
Project: related   Author: genomoncology   File: functions.py    License: 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
Project: casepro   Author: rapidpro   File: tests.py    License: 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 17
Project: edgedb   Author: edgedb   File: __init__.py    License: 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 18
Project: gpu-utils   Author: Ricks-Lab   File: GPUmodule.py    License: 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 19
Project: gated-graph-transformer-network   Author: hexahedria   File: util.py    License: MIT License 5 votes vote down vote up
def object_hash(thing):
    class EnumEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, enum.Enum):
                return obj.name
            return super().default(obj)
    strform = json.dumps(thing, sort_keys=True, cls=EnumEncoder)
    h = hashlib.sha1()
    h.update(strform.encode('utf-8'))
    return h.hexdigest() 
Example 20
Project: sphinx-quant   Author: sphinx-quant   File: const.py    License: MIT License 5 votes vote down vote up
def enum_to_choices(enum: Enum):
    """ cover enum to choice """
    return tuple([(tag.name, tag.value) for tag in enum]) 
Example 21
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    License: Apache License 2.0 5 votes vote down vote up
def _make_skeleton_enum(bases, name, qualname, members, module,
                        class_tracker_id, extra):
    """Build dynamic enum with an empty __dict__ to be filled once memoized

    The creation of the enum class is inspired by the code of
    EnumMeta._create_.

    If class_tracker_id is not None, try to lookup an existing enum definition
    matching that id. If none is found, track a newly reconstructed enum
    definition under that id so that other instances stemming from the same
    class id will also reuse this enum definition.

    The "extra" variable is meant to be a dict (or None) that can be used for
    forward compatibility shall the need arise.
    """
    # enums always inherit from their base Enum class at the last position in
    # the list of base classes:
    enum_base = bases[-1]
    metacls = enum_base.__class__
    classdict = metacls.__prepare__(name, bases)

    for member_name, member_value in members.items():
        classdict[member_name] = member_value
    enum_class = metacls.__new__(metacls, name, bases, classdict)
    enum_class.__module__ = module

    # Python 2.7 compat
    if qualname is not None:
        enum_class.__qualname__ = qualname

    return _lookup_class_or_track(class_tracker_id, enum_class) 
Example 22
Project: faxplus-python   Author: alohi   File: api_client.py    License: MIT License 5 votes vote down vote up
def __deserialize_model(self, data, klass):
        """Deserializes list or dict to model.

        :param data: dict, list.
        :param klass: class literal.
        :return: model object.
        """
        if issubclass(klass, Enum):
            return klass(data)

        if not klass.swagger_types and not self.__hasattr(klass, 'get_real_child_model'):
            return data

        kwargs = {}
        if klass.swagger_types is not None:
            for attr, attr_type in six.iteritems(klass.swagger_types):
                if (data is not None and
                        klass.attribute_map[attr] in data and
                        isinstance(data, (list, dict))):
                    value = data[klass.attribute_map[attr]]
                    kwargs[attr] = self.__deserialize(value, attr_type)

        instance = klass(**kwargs)

        if (isinstance(instance, dict) and
                klass.swagger_types is not None and
                isinstance(data, dict)):
            for key, value in data.items():
                if key not in klass.swagger_types:
                    instance[key] = value
        if self.__hasattr(instance, 'get_real_child_model'):
            klass_name = instance.get_real_child_model(data)
            if klass_name:
                instance = self.__deserialize(data, klass_name)
        return instance 
Example 23
Project: sslyze   Author: nabla-c0d3   File: json.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _enum_to_json(obj: Enum) -> JsonType:
    return obj.name 
Example 24
Project: misp42splunk   Author: remg427   File: enum_type.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, enum, use_values=False, **kwargs):
        """
        :param enum: Enum class to which restrict values assigned to the field.
        :param use_values: If true, also values of the enum (right-hand side) can be assigned here.
        Other args are passed to superclass.
        """
        self._enum_class = enum
        self._use_values = use_values
        super(EnumType, self).__init__(**kwargs) 
Example 25
Project: misp42splunk   Author: remg427   File: enum_type.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_primitive(self, value, context=None):
        if isinstance(value, Enum):
            if self._use_values:
                return value.value
            else:
                return value.name
        else:
            return str(value) 
Example 26
Project: misp42splunk   Author: remg427   File: enum_type.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, enum, use_values=False, **kwargs):
        """
        :param enum: Enum class to which restrict values assigned to the field.
        :param use_values: If true, also values of the enum (right-hand side) can be assigned here.
        Other args are passed to superclass.
        """
        self._enum_class = enum
        self._use_values = use_values
        super(EnumType, self).__init__(**kwargs) 
Example 27
Project: misp42splunk   Author: remg427   File: enum_type.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_primitive(self, value, context=None):
        if isinstance(value, Enum):
            if self._use_values:
                return value.value
            else:
                return value.name
        else:
            return str(value) 
Example 28
Project: tekore   Author: felix-hilden   File: scope.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Enum value."""
        return self.value 
Example 29
Project: tekore   Author: felix-hilden   File: serialise.py    License: MIT License 5 votes vote down vote up
def default(self, o):
        """Convert into serialisable data types."""
        if isinstance(o, (Enum, Timestamp)):
            return str(o)
        elif isinstance(o, Model):
            return asdict(o)
        else:
            return super().default(o) 
Example 30
Project: tekore   Author: felix-hilden   File: model.py    License: MIT License 5 votes vote down vote up
def test_enum_encoded_is_quoted_str(self):
        enum = Enum('enum', 'a b c')
        encoded = JSONEncoder().encode(enum.a)
        assert encoded == f'"{str(enum.a)}"'