MCPcopy Index your code
hub / github.com/pyscript/pyscript / __getitem__

Method __getitem__

core/src/stdlib/pyscript/web.py:1092–1125  ·  view source on GitHub ↗

Get items from the collection. Behaviour depends on the key type: - Integer: returns the element at that index. - Slice: returns a new collection with elements in that slice. - String: looks up an element by id (with or without '#' prefix). ```pyth

(self, key)

Source from the content-addressed store, hash-verified

1090 return isinstance(obj, ElementCollection) and obj._elements == self._elements
1091
1092 def __getitem__(self, key):
1093 """
1094 Get items from the collection.
1095
1096 Behaviour depends on the key type:
1097
1098 - Integer: returns the element at that index.
1099 - Slice: returns a new collection with elements in that slice.
1100 - String: looks up an element by id (with or without '#' prefix).
1101
1102 ```python
1103 collection[0] # First element.
1104 collection[1:3] # New collection with 2nd and 3rd elements.
1105 collection["my-id"] # Element with id="my-id" (or None).
1106 collection["#my-id"] # Same as above (# is optional).
1107 ```
1108 """
1109 if isinstance(key, int):
1110 return self._elements[key]
1111 if isinstance(key, slice):
1112 return ElementCollection(self._elements[key])
1113 if isinstance(key, str):
1114 for element in self._elements:
1115 element_id = key[1:] if key.startswith("#") else key
1116 if element.id == element_id:
1117 return element
1118 result = _find_by_id(element._dom_element, element_id)
1119 if result:
1120 return result
1121 return None
1122 raise TypeError(
1123 f"Collection indices must be integers, slices, or strings, "
1124 f"not {type(key).__name__}"
1125 )
1126
1127 def __iter__(self):
1128 yield from self._elements

Callers

nothing calls this directly

Calls 2

ElementCollectionClass · 0.85
_find_by_idFunction · 0.85

Tested by

no test coverage detected