Coverage for /home/runner/work/viur-core/viur-core/viur/src/viur/core/utils/parse.py: 93%

10 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-03 13:41 +0000

1""" 

2ViUR utility functions regarding parsing. 

3""" 

4import typing as t 

5import datetime 

6 

7 

8def bool(value: t.Any, truthy_values: t.Iterable[str] = ("true", "yes", "1")) -> bool: 

9 """ 

10 Parse a value into a boolean based on accepted truthy values. 

11 

12 This method takes a value, converts it to a lowercase string, 

13 removes whitespace, and checks if it matches any of the provided 

14 truthy values. 

15 :param value: The value to be parsed into a boolean. 

16 :param truthy_values: An iterable of strings representing truthy values. 

17 Default is ("true", "yes", "1"). 

18 :returns: True if the value matches any of the truthy values, False otherwise. 

19 """ 

20 return str(value).strip().lower() in truthy_values 

21 

22 

23def timedelta(value: datetime.timedelta | int | float | str) -> datetime.timedelta: 

24 """ 

25 Parse a value into a timedelta object. 

26 

27 This method takes a seconds value and converts it into 

28 a timedelta object, if it is not already one. 

29 :param value: The value to be parsed into a timedelta. 

30 :returns: A timedelta object. 

31 """ 

32 if isinstance(value, datetime.timedelta): 

33 return value 

34 if isinstance(value, str): 

35 value = float(value) 

36 return datetime.timedelta(seconds=value)