Coverage for /Users/coordt/Documents/code/bump-my-version/bumpversion/autocast.py: 0%
35 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-06-12 09:26 -0500
« prev ^ index » next coverage.py v7.4.4, created at 2024-06-12 09:26 -0500
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 homogeneous 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 homogeneous basic types.
43 Returns:
44 List of homogeneous basic types.
45 """
46 if "\n" in s:
47 str_list = s.strip().split("\n")
48 elif "," in s:
49 str_list = s.strip().split(",")
50 else:
51 raise ValueError("Not a List")
53 # derive the type of the variable
54 element_caster = str
55 for caster in (boolify, int, float, noneify, element_caster):
56 with contextlib.suppress(ValueError):
57 caster(str_list[0]) # type: ignore[operator]
58 element_caster = caster # type: ignore[assignment]
59 break
60 # cast all elements
61 try:
62 return [element_caster(x) for x in str_list]
63 except ValueError as e:
64 raise TypeError("Autocasted list must be all same type") from e
67def autocast_value(var: Any) -> Any:
68 """
69 Guess the string representation of the variable's type.
71 Args:
72 var: Value to autocast.
74 Returns:
75 The autocasted value.
76 """
77 if not isinstance(var, str): # don't need to guess non-string types
78 return var
80 # guess string representation of var
81 for caster in (boolify, int, float, noneify, listify):
82 with contextlib.suppress(ValueError):
83 return caster(var) # type: ignore[operator]
85 return var