A priority sorted registry. A `Registry` instance provides two public methods to alter the data of the registry: `register` and `deregister`. Use `register` to add items and `deregister` to remove items. See each method for specifics. When registering an item, a "name" and a "
| 271 | |
| 272 | |
| 273 | class Registry(Generic[_T]): |
| 274 | """ |
| 275 | A priority sorted registry. |
| 276 | |
| 277 | A `Registry` instance provides two public methods to alter the data of the |
| 278 | registry: `register` and `deregister`. Use `register` to add items and |
| 279 | `deregister` to remove items. See each method for specifics. |
| 280 | |
| 281 | When registering an item, a "name" and a "priority" must be provided. All |
| 282 | items are automatically sorted by "priority" from highest to lowest. The |
| 283 | "name" is used to remove ("deregister") and get items. |
| 284 | |
| 285 | A `Registry` instance it like a list (which maintains order) when reading |
| 286 | data. You may iterate over the items, get an item and get a count (length) |
| 287 | of all items. You may also check that the registry contains an item. |
| 288 | |
| 289 | When getting an item you may use either the index of the item or the |
| 290 | string-based "name". For example: |
| 291 | |
| 292 | registry = Registry() |
| 293 | registry.register(SomeItem(), 'itemname', 20) |
| 294 | # Get the item by index |
| 295 | item = registry[0] |
| 296 | # Get the item by name |
| 297 | item = registry['itemname'] |
| 298 | |
| 299 | When checking that the registry contains an item, you may use either the |
| 300 | string-based "name", or a reference to the actual item. For example: |
| 301 | |
| 302 | someitem = SomeItem() |
| 303 | registry.register(someitem, 'itemname', 20) |
| 304 | # Contains the name |
| 305 | assert 'itemname' in registry |
| 306 | # Contains the item instance |
| 307 | assert someitem in registry |
| 308 | |
| 309 | The method `get_index_for_name` is also available to obtain the index of |
| 310 | an item using that item's assigned "name". |
| 311 | """ |
| 312 | |
| 313 | def __init__(self): |
| 314 | self._data: dict[str, _T] = {} |
| 315 | self._priority: list[_PriorityItem] = [] |
| 316 | self._is_sorted = False |
| 317 | |
| 318 | def __contains__(self, item: str | _T) -> bool: |
| 319 | if isinstance(item, str): |
| 320 | # Check if an item exists by this name. |
| 321 | return item in self._data.keys() |
| 322 | # Check if this instance exists. |
| 323 | return item in self._data.values() |
| 324 | |
| 325 | def __iter__(self) -> Iterator[_T]: |
| 326 | self._sort() |
| 327 | return iter([self._data[k] for k, p in self._priority]) |
| 328 | |
| 329 | @overload |
| 330 | def __getitem__(self, key: str | int) -> _T: # pragma: no cover |
no outgoing calls
no test coverage detected
searching dependent graphs…