def __getitem__(self, key): # if key is a slice, raise ProtocolUnbound if isinstance(key, slice): raise ProtocolUnbound('protocol slice unbound') # if key is a protocol, then fetch protocol indexes try: flag = issubclass(key, Protocol) except TypeError: flag = issubclass(type(key), Protocol) if flag or isinstance(key, Protocol): key = key.__index__() # make regex for tuple indexes if isinstance(key, tuple): key = r'|'.join(map(re.escape, key)) # if it's itself if re.fullmatch(key, self.__class__.__name__, re.IGNORECASE): return self # then check recursively from pcapkit.protocols.null import NoPayload payload = self._next while not isinstance(payload, NoPayload): if re.fullmatch(key, payload.__class__.__name__, re.IGNORECASE): return payload payload = payload.payload raise ProtocolNotFound(f"Layer {key!r} not in Frame")
def __getitem__(self, key): """Subscription (``getitem``) support. * If ``key`` is a ``slice`` object, :exc:`ProtocolUnbound` will be raised. * If ``key`` is a :class`~pcapkit.protocols.protocol.Protocol` object, the method will fetch its indexes (:meth`~pcapkit.protocols.protocol.Protocol.__index__`). * Later, search the packet's chain of protocols with the calculated ``key``. * If no matches, then raises :exc:`ProtocolNotFound`. Args: key (Union[str, Protocol, Type[Protocol]]): Indexing key. Returns: Protocol: The sub-packet from the current packet of indexed protocol. Raises: ProtocolUnbound: If ``key`` is a ``slice`` object. ProtocolNotFound: If ``key`` is not in the current packet. """ # if key is a slice, raise ProtocolUnbound if isinstance(key, slice): raise ProtocolUnbound('protocol slice unbound') # if key is a protocol, then fetch protocol indexes try: flag = issubclass(key, Protocol) except TypeError: flag = issubclass(type(key), Protocol) if flag or isinstance(key, Protocol): key = key.__index__() # make regex for tuple indexes if isinstance(key, tuple): key = r'|'.join(map(re.escape, key)) # if it's itself if re.fullmatch(key, self.__class__.__name__, re.IGNORECASE): return self # then check recursively from pcapkit.protocols.null import NoPayload # pylint: disable=import-outside-toplevel payload = self._next while not isinstance(payload, NoPayload): if re.fullmatch(key, payload.__class__.__name__, re.IGNORECASE): return payload payload = payload.payload raise ProtocolNotFound(f"Layer {key!r} not in Frame")