Coverage for tsfpga/module_list.py: 97%
35 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-21 20:51 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-21 20:51 +0000
1# --------------------------------------------------------------------------------------------------
2# Copyright (c) Lukas Vik. All rights reserved.
3#
4# This file is part of the tsfpga project, a project platform for modern FPGA development.
5# https://tsfpga.com
6# https://github.com/tsfpga/tsfpga
7# --------------------------------------------------------------------------------------------------
9import copy
10from collections.abc import Iterator
11from typing import TYPE_CHECKING
13if TYPE_CHECKING:
14 from .module import BaseModule
17class ModuleList:
18 """
19 Wrapper for a list of modules, with convenience functions.
20 """
22 def __init__(self) -> None:
23 self._modules: list[BaseModule] = []
25 def append(self, module: "BaseModule") -> None:
26 """
27 Append a module to the list.
28 """
29 self._modules.append(module)
31 def get(self, module_name: "str") -> "BaseModule":
32 """
33 Get the module with the specified name. If no module matched, an exception is raised.
34 """
35 for module in self._modules:
36 if module.name == module_name:
37 return module
39 raise ValueError(f'No module "{module_name}" available')
41 def __iter__(self) -> Iterator["BaseModule"]:
42 return iter(self._modules)
44 def __getitem__(self, index: int) -> "BaseModule":
45 return self._modules[index]
47 def __len__(self) -> int:
48 return len(self._modules)
50 def __add__(self, other: "ModuleList") -> "ModuleList":
51 if not isinstance(other, self.__class__):
52 raise TypeError(f"Can only concatenate with another {self.__class__.__name__}")
54 # Note that the list concatenation implies a shallow copy of the lists
55 result = self.__class__()
56 result._modules = self._modules + other._modules
57 return result
59 def __copy__(self) -> "ModuleList":
60 result = self.__class__()
61 result._modules = self._modules.copy() # noqa: SLF001
62 return result
64 def copy(self) -> "ModuleList":
65 """
66 Create a shallow copy of the module list. This public function is available as a
67 convenience and to mimic the interface of a regular python list.
68 """
69 return copy.copy(self)
71 def __str__(self) -> str:
72 return str(self._modules)