Coverage for src/_griffe/collections.py: 94.29%
33 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-15 16:47 +0200
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-15 16:47 +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, ItemsView, KeysView, ValuesView
8from _griffe.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin
10if TYPE_CHECKING:
11 from pathlib import Path
13 from _griffe.models import Module
16class LinesCollection:
17 """A simple dictionary containing the modules source code lines."""
19 def __init__(self) -> None:
20 """Initialize the collection."""
21 self._data: dict[Path, list[str]] = {}
23 def __getitem__(self, key: Path) -> list[str]:
24 """Get the lines of a file path."""
25 return self._data[key]
27 def __setitem__(self, key: Path, value: list[str]) -> None:
28 """Set the lines of a file path."""
29 self._data[key] = value
31 def __contains__(self, item: Path) -> bool:
32 """Check if a file path is in the collection."""
33 return item in self._data
35 def __bool__(self) -> bool:
36 """A lines collection is always true-ish."""
37 return True
39 def keys(self) -> KeysView:
40 """Return the collection keys.
42 Returns:
43 The collection keys.
44 """
45 return self._data.keys()
47 def values(self) -> ValuesView:
48 """Return the collection values.
50 Returns:
51 The collection values.
52 """
53 return self._data.values()
55 def items(self) -> ItemsView:
56 """Return the collection items.
58 Returns:
59 The collection items.
60 """
61 return self._data.items()
64class ModulesCollection(GetMembersMixin, SetMembersMixin, DelMembersMixin):
65 """A collection of modules, allowing easy access to members."""
67 is_collection = True
68 """Marked as collection to distinguish from objects."""
70 def __init__(self) -> None:
71 """Initialize the collection."""
72 self.members: dict[str, Module] = {}
73 """Members (modules) of the collection."""
75 def __bool__(self) -> bool:
76 """A modules collection is always true-ish."""
77 return True
79 def __contains__(self, item: Any) -> bool:
80 """Check if a module is in the collection."""
81 return item in self.members
83 @property
84 def all_members(self) -> dict[str, Module]:
85 """Members of the collection.
87 This property is overwritten to simply return `self.members`,
88 as `all_members` does not make sense for a modules collection.
89 """
90 return self.members