本文整理匯總了Python中enum.Enum方法的典型用法代碼示例。如果您正苦於以下問題:Python enum.Enum方法的具體用法?Python enum.Enum怎麽用?Python enum.Enum使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類enum
的用法示例。
在下文中一共展示了enum.Enum方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_openapi_operation_parameters
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例2: get_openapi_operation_request_body
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例3: ask_remove_enum_values
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例4: get_value_sql
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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)
示例5: _save_dynamic_enum
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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)
示例6: decode
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例7: test_type_conv_invalid
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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)
示例8: enum_process_names
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例9: todict
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例10: ir_to_string
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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())
+ ')')
示例11: send_signal
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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.")
示例12: prepare_for_json
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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
示例13: default
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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)
示例14: to_python
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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__))
示例15: to_model
# 需要導入模塊: import enum [as 別名]
# 或者: from enum import Enum [as 別名]
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