Coverage for gws-app/gws/plugin/model_value/expression/__init__.py: 0%

32 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-16 23:09 +0200

1"""Expression value. 

2 

3This value is computed by evaluating a python expression. 

4 

5The following variables are provided to the expression: 

6 

7- ``app`` - the Application object 

8- ``user`` - current user 

9- ``project`` - current project 

10- ``feature`` - feature this value is evaluated for 

11- ``mc`` - ``ModelContext`` object 

12 

13The following modules are available: 

14 

15- ``date`` - `gws.lib.datetimex` module 

16 

17Additional modules can be imported by specifying them in the 

18``imports`` configuration option. This should be a list of module names 

19to import, e.g. ``["math", "os"]``. 

20 

21""" 

22 

23from typing import Optional 

24import gws 

25import gws.base.model.value 

26import gws.lib.datetimex 

27 

28gws.ext.new.modelValue('expression') 

29 

30 

31class Config(gws.base.model.value.Config): 

32 """Expression-based value.""" 

33 

34 expression: str 

35 """Python expression to evaluate.""" 

36 

37 imports: Optional[list[str]] 

38 """List of additional modules to import. (added in 8.2)""" 

39 

40 

41class Object(gws.base.model.value.Object): 

42 expression: str 

43 imports: list[str] 

44 

45 def configure(self): 

46 self.expression = (self.cfg('expression') or '').strip() 

47 self.imports = self.cfg('imports') or [] 

48 try: 

49 compile(self.expression, 'expression', 'eval') 

50 except Exception as exc: 

51 raise gws.ConfigurationError(f'invalid expression: {exc!r}') from exc 

52 

53 def compute(self, field, feature, mc): 

54 context = { 

55 'app': self.root.app, 

56 'user': mc.user, 

57 'project': mc.project, 

58 'feature': feature, 

59 'mc': mc, 

60 'date': gws.lib.datetimex, 

61 } 

62 for mod in self.imports: 

63 try: 

64 context[mod] = __import__(mod) 

65 except ImportError as exc: 

66 gws.log.error(f'failed to import module {mod!r}: {exc!r}') 

67 return 

68 

69 try: 

70 return eval(self.expression, context) 

71 except Exception as exc: 

72 gws.log.error(f'failed to compute expression: {exc!r}')