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

1# This module contains collection-related classes, 

2# which are used throughout the API. 

3 

4from __future__ import annotations 

5 

6from typing import TYPE_CHECKING, Any, ItemsView, KeysView, ValuesView 

7 

8from _griffe.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin 

9 

10if TYPE_CHECKING: 

11 from pathlib import Path 

12 

13 from _griffe.models import Module 

14 

15 

16class LinesCollection: 

17 """A simple dictionary containing the modules source code lines.""" 

18 

19 def __init__(self) -> None: 

20 """Initialize the collection.""" 

21 self._data: dict[Path, list[str]] = {} 

22 

23 def __getitem__(self, key: Path) -> list[str]: 

24 """Get the lines of a file path.""" 

25 return self._data[key] 

26 

27 def __setitem__(self, key: Path, value: list[str]) -> None: 

28 """Set the lines of a file path.""" 

29 self._data[key] = value 

30 

31 def __contains__(self, item: Path) -> bool: 

32 """Check if a file path is in the collection.""" 

33 return item in self._data 

34 

35 def __bool__(self) -> bool: 

36 """A lines collection is always true-ish.""" 

37 return True 

38 

39 def keys(self) -> KeysView: 

40 """Return the collection keys. 

41 

42 Returns: 

43 The collection keys. 

44 """ 

45 return self._data.keys() 

46 

47 def values(self) -> ValuesView: 

48 """Return the collection values. 

49 

50 Returns: 

51 The collection values. 

52 """ 

53 return self._data.values() 

54 

55 def items(self) -> ItemsView: 

56 """Return the collection items. 

57 

58 Returns: 

59 The collection items. 

60 """ 

61 return self._data.items() 

62 

63 

64class ModulesCollection(GetMembersMixin, SetMembersMixin, DelMembersMixin): 

65 """A collection of modules, allowing easy access to members.""" 

66 

67 is_collection = True 

68 """Marked as collection to distinguish from objects.""" 

69 

70 def __init__(self) -> None: 

71 """Initialize the collection.""" 

72 self.members: dict[str, Module] = {} 

73 """Members (modules) of the collection.""" 

74 

75 def __bool__(self) -> bool: 

76 """A modules collection is always true-ish.""" 

77 return True 

78 

79 def __contains__(self, item: Any) -> bool: 

80 """Check if a module is in the collection.""" 

81 return item in self.members 

82 

83 @property 

84 def all_members(self) -> dict[str, Module]: 

85 """Members of the collection. 

86 

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