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 2023-12-10 08:09 -0600
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-10 08:09 -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
5"""
7import contextlib
8from typing import Any
11def boolify(s: str) -> bool:
12 """Convert a string to a boolean."""
13 if s in {"True", "true"}:
14 return True
15 if s in {"False", "false"}:
16 return False
17 raise ValueError("Not Boolean Value!")
20def noneify(s: str) -> None:
21 """Convert a string to None."""
22 if s == "None":
23 return None
24 raise ValueError("Not None Value!")
27def listify(s: str) -> list:
28 """
29 Convert a string representation of a list into list of homogenous basic types.
31 Type of elements in list is determined via first element. Successive elements are
32 cast to that type.
34 Args:
35 s: String representation of a list.
37 Raises:
38 ValueError: If string does not represent a list.
39 TypeError: If string does not represent a list of homogenous basic types.
41 Returns:
42 List of homogenous basic types.
43 """
44 if "," not in s and "\n" not in s:
45 raise ValueError("Not a List")
47 # derive the type of the variable
48 str_list = s.strip().split(",") if "," in s else s.strip().split("\n")
49 element_caster = str
50 for caster in (boolify, int, float, noneify, element_caster):
51 with contextlib.suppress(ValueError):
52 caster(str_list[0]) # type: ignore[operator]
53 element_caster = caster # type: ignore[assignment]
54 break
55 # cast all elements
56 try:
57 return [element_caster(x) for x in str_list]
58 except ValueError as e:
59 raise TypeError("Autocasted list must be all same type") from e
62def autocast_value(var: Any) -> Any:
63 """
64 Guess the string representation of the variable's type.
66 Args:
67 var: Value to autocast.
69 Returns:
70 The autocasted value.
71 """
72 if not isinstance(var, str): # don't need to guess non-string types
73 return var
75 # guess string representation of var
76 for caster in (boolify, int, float, noneify, listify):
77 with contextlib.suppress(ValueError):
78 return caster(var) # type: ignore[operator]
80 return var