Coverage for pySDC/core/common.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2024-12-20 14:51 +0000

1#!/usr/bin/env python3 

2# -*- coding: utf-8 -*- 

3""" 

4Description 

5----------- 

6 

7Module containing utility classe(s) from which inherit some of the pySDC base 

8classes. 

9""" 

10from pySDC.core.errors import ReadOnlyError 

11 

12 

13class _MetaRegisterParams(type): 

14 """Metaclass for RegisterParams base class""" 

15 

16 def __new__(cls, name, bases, dct): 

17 obj = super().__new__(cls, name, bases, dct) 

18 obj._parNamesReadOnly = set() 

19 obj._parNames = set() 

20 return obj 

21 

22 

23class RegisterParams(metaclass=_MetaRegisterParams): 

24 """ 

25 Base class to register parameters. 

26 

27 Attributes 

28 ---------- 

29 params : dict (property) 

30 Dictionary containing names and values of registered parameters. 

31 _parNames : set of str 

32 Names of all the registered parameters. 

33 _parNamesReadOnly : set of str 

34 Names of all the parameters registered as read-only. 

35 """ 

36 

37 def _makeAttributeAndRegister(self, *names, localVars=None, readOnly=False): 

38 """ 

39 Register a list of attribute name as parameters of the class. 

40 

41 Parameters 

42 ---------- 

43 *names : list of str 

44 The name of the parameters to be registered (should be class attributes). 

45 localVars : dict 

46 Dictionary containing key=names and values=paramValues for each 

47 parNames given in names. Can be provided, for instance, using 

48 `locals()` built-in dictionary. MUST BE provided as soon as 

49 names contains anything. 

50 readOnly : bool, optional 

51 Wether or not store the parameters as read-only attributes 

52 """ 

53 if len(names) > 1 and localVars is None: 

54 raise ValueError("a dictionary must be provided in localVars with parameters values") 

55 # Set parameters as attributes 

56 for name in names: 

57 try: 

58 super().__setattr__(name, localVars[name]) 

59 except KeyError as e: # pragma: no cover 

60 raise ValueError(f'value for {name} not given in localVars') from e 

61 # Register as class parameter 

62 if readOnly: 

63 self._parNamesReadOnly = self._parNamesReadOnly.union(names) 

64 else: 

65 self._parNames = self._parNames.union(names) 

66 

67 @property 

68 def params(self): 

69 """Dictionary containing names and values of registered parameters""" 

70 return {name: getattr(self, name) for name in self._parNamesReadOnly.union(self._parNames)} 

71 

72 def __setattr__(self, name, value): 

73 if name in self._parNamesReadOnly: 

74 raise ReadOnlyError(name) 

75 super().__setattr__(name, value)