Coverage for /Users/OORDCOR/Documents/code/bump-my-version/bumpversion/autocast.py: 0%
33 statements
« prev ^ index » next coverage.py v7.3.2, created at 2024-02-24 07:45 -0600
« prev ^ index » next coverage.py v7.3.2, created at 2024-02-24 07:45 -0600
1"""
2Automatically detect the true Python type of a string and cast it to the correct type.
4Based on https://github.com/cgreer/cgAutoCast/blob/master/cgAutoCast.py
6Only used by Legacy configuration file parser.
7"""
9import contextlib
10from typing import Any
13def 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!")
22def noneify(s: str) -> None:
23 """Convert a string to None."""
24 if s == "None":
25 return None
26 raise ValueError("Not None Value!")
29def listify(s: str) -> list:
30 """
31 Convert a string representation of a list into list of homogenous basic types.
33 Type of elements in list is determined via first element. Successive elements are
34 cast to that type.
36 Args:
37 s: String representation of a list.
39 Raises:
40 ValueError: If string does not represent a list.
41 TypeError: If string does not represent a list of homogenous basic types.
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")
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
64def autocast_value(var: Any) -> Any:
65 """
66 Guess the string representation of the variable's type.
68 Args:
69 var: Value to autocast.
71 Returns:
72 The autocasted value.
73 """
74 if not isinstance(var, str): # don't need to guess non-string types
75 return var
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]
82 return var