Coverage for /Users/OORDCOR/Documents/code/bump-my-version/bumpversion/autocast.py: 0%

1"""

2 Automatically detect the true Python type of a string and cast it to the correct type.

3

4 Based on https://github.com/cgreer/cgAutoCast/blob/master/cgAutoCast.py

5

6 Only used by Legacy configuration file parser.

7"""

8

9 import contextlib

10 from typing import Any

11

12

13 def boolify(s: str) -> bool:

14 """Convert a string to a boolean."""

15 if s in {"True", "true"}:

16 return True

17 if s in {"False", "false"}:

18 return False

19 raise ValueError("Not Boolean Value!")

20

21

22 def noneify(s: str) -> None:

23 """Convert a string to None."""

24 if s == "None":

25 return None

26 raise ValueError("Not None Value!")

27

28

29 def listify(s: str) -> list:

30 """

31 Convert a string representation of a list into list of homogenous basic types.

32

33 Type of elements in list is determined via first element. Successive elements are

34 cast to that type.

35

36 Args:

37 s: String representation of a list.

38

39 Raises:

40 ValueError: If string does not represent a list.

41 TypeError: If string does not represent a list of homogenous basic types.

42

43 Returns:

44 List of homogenous basic types.

45 """

46 if "," not in s and "\n" not in s:

47 raise ValueError("Not a List")

48

49 # derive the type of the variable

50 str_list = s.strip().split(",") if "," in s else s.strip().split("\n")

51 element_caster = str

52 for caster in (boolify, int, float, noneify, element_caster):

53 with contextlib.suppress(ValueError):

54 caster(str_list[0]) # type: ignore[operator]

55 element_caster = caster # type: ignore[assignment]

56 break

57 # cast all elements

58 try:

59 return [element_caster(x) for x in str_list]

60 except ValueError as e:

61 raise TypeError("Autocasted list must be all same type") from e

62

63

64 def autocast_value(var: Any) -> Any:

65 """

66 Guess the string representation of the variable's type.

67

68 Args:

69 var: Value to autocast.

70

71 Returns:

72 The autocasted value.

73 """

74 if not isinstance(var, str): # don't need to guess non-string types

75 return var

76

77 # guess string representation of var

78 for caster in (boolify, int, float, noneify, listify):

79 with contextlib.suppress(ValueError):

80 return caster(var) # type: ignore[operator]

81

82 return var