Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
Union[int, bytes]: Index of ``name`` from a dict or enumeration.
If ``packet`` is :data:`True`, returns :obj:`bytes`; otherwise,
returns :obj:`int`.
Raises:
ProtocolNotImplemented: If ``name`` is **NOT** in ``namespace``
and ``default`` is :data:`None`.
"""
if isinstance(name, (enum.IntEnum, aenum.IntEnum)):
index = name.value
elif isinstance(name, numbers.Integral):
index = name
else:
try:
if isinstance(namespace, (enum.EnumMeta, aenum.EnumMeta)):
index = namespace[name]
elif isinstance(namespace, (dict, collections.UserDict, collections.abc.Mapping)):
if reversed:
index = namespace[name]
else:
index = {v: k for k, v in namespace.items()}[name]
else:
raise KeyError
except KeyError:
if default is None:
raise ProtocolNotImplemented(f'protocol {name!r} not implemented') from None
index = default
if pack:
return cls._make_pack(index, size=size, signed=signed, lilendian=lilendian)
return index
Keyword arguments:
* namespace -- dict / EnumMeta, namespace for item
* reversed -- bool, if namespace is [str -> int] pairs
* pack -- bool, if need struct.pack
* size -- int, buffer size (default is 4)
* signed -- bool, signed flag (default is False)
* lilendian -- bool, little-endian flag (default is False)
"""
if isinstance(name, (enum.IntEnum, aenum.IntEnum)):
index = name.value
elif isinstance(name, numbers.Integral):
index = name
else:
try:
if isinstance(namespace, (enum.EnumMeta, aenum.EnumMeta)):
index = namespace[name]
elif isinstance(namespace, (dict, collections.UserDict, collections.abc.Mapping)):
if reversed:
index = namespace[name]
else:
index = {v: k for k, v in namespace.items()}[name]
else:
raise KeyError
except KeyError:
if default is None:
raise ProtocolNotImplemented(f'protocol {name!r} not implemented') from None
index = default
if pack:
return cls.pack(index, size=size, signed=signed, lilendian=lilendian)
return index
def enum_check(*args, stacklevel=2):
"""Check if arguments are of protocol type."""
for var in args:
if not isinstance(var, (enum.EnumMeta, aenum.EnumMeta)):
name = type(var).__name__
func = inspect.stack()[stacklevel][3]
raise EnumError('Function {} expected enumeration, {} got instead.'.format(func, name))
def enum_check(*args, stacklevel=2):
"""Check if arguments are of *enumeration protocol* type (``enum.EnumMeta`` and/or ``aenum.EnumMeta``).
Args:
*args: Arguments to check.
stacklevel (int): Stack level to fetch originated function name.
Raises:
EnumError: If any of the arguments is **NOT** *enumeration protocol* type
(``enum.EnumMeta`` and/or ``aenum.EnumMeta``).
"""
for var in args:
if not isinstance(var, (enum.EnumMeta, aenum.EnumMeta)):
name = type(var).__name__
func = inspect.stack()[stacklevel][3]
raise EnumError(f'Function {func} expected enumeration, {name} got instead.')