Coverage for tsfpga/module_list.py: 97%

34 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-07 11:31 +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# -------------------------------------------------------------------------------------------------- 

8 

9# Standard libraries 

10import copy 

11from typing import TYPE_CHECKING, Iterator 

12 

13if TYPE_CHECKING: 

14 # Local folder libraries 

15 from .module import BaseModule 

16 

17 

18class ModuleList: 

19 """ 

20 Wrapper for a list of modules, with convenience functions. 

21 """ 

22 

23 def __init__(self) -> None: 

24 self._modules: list["BaseModule"] = [] 

25 

26 def append(self, module: "BaseModule") -> None: 

27 """ 

28 Append a module to the list. 

29 """ 

30 self._modules.append(module) 

31 

32 def get(self, module_name: "str") -> "BaseModule": 

33 """ 

34 Get the module with the specified name. If no module matched, an exception is raised. 

35 """ 

36 for module in self._modules: 

37 if module.name == module_name: 

38 return module 

39 

40 raise ValueError(f'No module "{module_name}" available') 

41 

42 def __iter__(self) -> Iterator["BaseModule"]: 

43 return iter(self._modules) 

44 

45 def __getitem__(self, index: int) -> "BaseModule": 

46 return self._modules[index] 

47 

48 def __len__(self) -> int: 

49 return len(self._modules) 

50 

51 def __add__(self, other: "ModuleList") -> "ModuleList": 

52 if not isinstance(other, self.__class__): 

53 raise TypeError(f"Can only concatenate with another {self.__class__.__name__}") 

54 

55 # Note that the list concatenation implies a shallow copy of the lists 

56 result = self.__class__() 

57 result._modules = self._modules + other._modules 

58 return result 

59 

60 def __copy__(self) -> "ModuleList": 

61 result = self.__class__() 

62 result._modules = self._modules.copy() 

63 return result 

64 

65 def copy(self) -> "ModuleList": 

66 """ 

67 Create a shallow copy of the module list. This public function is available as a 

68 convenience and to mimic the interface of a regular python list. 

69 """ 

70 return copy.copy(self) 

71 

72 def __str__(self) -> str: 

73 return str(self._modules)