Coverage for src/_griffe/collections.py: 93.94%
33 statements
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
1# This module contains collection-related classes,
2# which are used throughout the API.
4from __future__ import annotations
6from typing import TYPE_CHECKING, Any
8from _griffe.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin
10if TYPE_CHECKING:
11 from collections.abc import ItemsView, KeysView, ValuesView
12 from pathlib import Path
14 from _griffe.models import Module
17class LinesCollection:
18 """A simple dictionary containing the modules source code lines."""
20 def __init__(self) -> None:
21 """Initialize the collection."""
22 self._data: dict[Path, list[str]] = {}
24 def __getitem__(self, key: Path) -> list[str]:
25 """Get the lines of a file path."""
26 return self._data[key]
28 def __setitem__(self, key: Path, value: list[str]) -> None:
29 """Set the lines of a file path."""
30 self._data[key] = value
32 def __contains__(self, item: Path) -> bool:
33 """Check if a file path is in the collection."""
34 return item in self._data
36 def __bool__(self) -> bool:
37 """A lines collection is always true-ish."""
38 return True
40 def keys(self) -> KeysView:
41 """Return the collection keys.
43 Returns:
44 The collection keys.
45 """
46 return self._data.keys()
48 def values(self) -> ValuesView:
49 """Return the collection values.
51 Returns:
52 The collection values.
53 """
54 return self._data.values()
56 def items(self) -> ItemsView:
57 """Return the collection items.
59 Returns:
60 The collection items.
61 """
62 return self._data.items()
65class ModulesCollection(GetMembersMixin, SetMembersMixin, DelMembersMixin):
66 """A collection of modules, allowing easy access to members."""
68 is_collection = True
69 """Marked as collection to distinguish from objects."""
71 def __init__(self) -> None:
72 """Initialize the collection."""
73 self.members: dict[str, Module] = {}
74 """Members (modules) of the collection."""
76 def __bool__(self) -> bool:
77 """A modules collection is always true-ish."""
78 return True
80 def __contains__(self, item: Any) -> bool:
81 """Check if a module is in the collection."""
82 return item in self.members
84 @property
85 def all_members(self) -> dict[str, Module]:
86 """Members of the collection.
88 This property is overwritten to simply return `self.members`,
89 as `all_members` does not make sense for a modules collection.
90 """
91 return self.members