strcoerce 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
strcoerce/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ from strcoerce._core import (
2
+ ParseError,
3
+ parse_bool,
4
+ parse_duration,
5
+ parse_float,
6
+ parse_int,
7
+ parse_list,
8
+ )
9
+
10
+ __version__ = "0.1.0"
11
+ __all__ = [
12
+ "ParseError",
13
+ "parse_bool",
14
+ "parse_duration",
15
+ "parse_float",
16
+ "parse_int",
17
+ "parse_list",
18
+ ]
strcoerce/_core.py ADDED
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from datetime import timedelta
5
+ from typing import Any
6
+
7
+ _MISSING: Any = object()
8
+
9
+ _TRUE_VALUES = frozenset({"1", "true", "yes", "on", "t", "y"})
10
+ _FALSE_VALUES = frozenset({"0", "false", "no", "off", "f", "n"})
11
+
12
+ # Matches combinations of Nw Nd Nh Nm Ns — all groups optional but at least one must be present
13
+ _DURATION_RE = re.compile(
14
+ r"^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$",
15
+ re.IGNORECASE,
16
+ )
17
+
18
+
19
+ class ParseError(ValueError):
20
+ """Raised when a string cannot be coerced into the requested type."""
21
+
22
+
23
+ def parse_bool(s: str, *, default: bool = _MISSING) -> bool:
24
+ """Parse a string to bool.
25
+
26
+ Accepted truthy: 1, true, yes, on, t, y (case-insensitive)
27
+ Accepted falsy: 0, false, no, off, f, n (case-insensitive)
28
+
29
+ Raises ParseError if the value is unrecognized and no default is given.
30
+ Raises TypeError if s is not a str.
31
+ """
32
+ if not isinstance(s, str):
33
+ raise TypeError(f"Expected str, got {type(s).__name__!r}")
34
+ normalized = s.strip().lower()
35
+ if normalized in _TRUE_VALUES:
36
+ return True
37
+ if normalized in _FALSE_VALUES:
38
+ return False
39
+ if default is not _MISSING:
40
+ return default
41
+ raise ParseError(
42
+ f"Cannot parse {s!r} as bool. "
43
+ f"Accepted values: {sorted(_TRUE_VALUES | _FALSE_VALUES)}"
44
+ )
45
+
46
+
47
+ def parse_int(s: str, *, default: int = _MISSING, base: int = 10) -> int:
48
+ """Parse a string to int.
49
+
50
+ Raises ParseError on failure unless default is given.
51
+ Pass base=16 for hex strings (e.g. 'ff' or '0xff').
52
+ """
53
+ if not isinstance(s, str):
54
+ raise TypeError(f"Expected str, got {type(s).__name__!r}")
55
+ try:
56
+ return int(s.strip(), base)
57
+ except ValueError:
58
+ if default is not _MISSING:
59
+ return default
60
+ raise ParseError(f"Cannot parse {s!r} as int") from None
61
+
62
+
63
+ def parse_float(s: str, *, default: float = _MISSING) -> float:
64
+ """Parse a string to float.
65
+
66
+ Raises ParseError on failure unless default is given.
67
+ """
68
+ if not isinstance(s, str):
69
+ raise TypeError(f"Expected str, got {type(s).__name__!r}")
70
+ try:
71
+ return float(s.strip())
72
+ except ValueError:
73
+ if default is not _MISSING:
74
+ return default
75
+ raise ParseError(f"Cannot parse {s!r} as float") from None
76
+
77
+
78
+ def parse_list(s: str, sep: str = ",", *, strip: bool = True) -> list[str]:
79
+ """Split a delimited string into a list, filtering empty strings.
80
+
81
+ parse_list("a, b, c") -> ["a", "b", "c"]
82
+ parse_list("a|b|c", sep="|") -> ["a", "b", "c"]
83
+ parse_list("") -> []
84
+ """
85
+ if not s.strip():
86
+ return []
87
+ items = s.split(sep)
88
+ if strip:
89
+ items = [item.strip() for item in items]
90
+ return [item for item in items if item]
91
+
92
+
93
+ def parse_duration(s: str) -> timedelta:
94
+ """Parse a compact duration string to timedelta.
95
+
96
+ Format: any combination of Nw Nd Nh Nm Ns (weeks/days/hours/minutes/seconds).
97
+ Examples: '30s', '5m', '2h30m', '1d12h', '1w2d3h4m5s'
98
+
99
+ Raises ParseError on unrecognized format.
100
+ """
101
+ s = s.strip()
102
+ if not s:
103
+ raise ParseError("Cannot parse empty string as duration")
104
+ match = _DURATION_RE.match(s)
105
+ if not match or not any(match.groups()):
106
+ raise ParseError(
107
+ f"Cannot parse {s!r} as duration. "
108
+ "Expected format like '30s', '5m', '2h30m', '1d12h', '1w'"
109
+ )
110
+ weeks, days, hours, minutes, seconds = (int(g or 0) for g in match.groups())
111
+ return timedelta(weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds)
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: strcoerce
3
+ Version: 0.1.0
4
+ Summary: Safe string-to-type coercion — parse_bool, parse_int, parse_float, parse_list, parse_duration
5
+ Project-URL: Homepage, https://github.com/SpinnakerSix/strcoerce
6
+ Project-URL: Issues, https://github.com/SpinnakerSix/strcoerce/issues
7
+ Project-URL: Changelog, https://github.com/SpinnakerSix/strcoerce/blob/main/CHANGELOG.md
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: bool,coerce,convert,environment,parse,string,type
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Utilities
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+
25
+ # strcoerce
26
+
27
+ Safe string-to-type coercion for Python. Zero dependencies.
28
+
29
+ ## The problem
30
+
31
+ ```python
32
+ import os
33
+ DEBUG = bool(os.environ.get("DEBUG", "false")) # Always True — "false" is a non-empty string
34
+ ```
35
+
36
+ `bool("false")` is `True` in Python. This catches experienced developers off guard and is a
37
+ [documented trap](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) with no
38
+ stdlib fix.
39
+
40
+ ## Install
41
+
42
+ ```
43
+ pip install strcoerce
44
+ ```
45
+
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from strcoerce import parse_bool, parse_int, parse_float, parse_list, parse_duration
51
+
52
+ # Environment variables
53
+ DEBUG = parse_bool(os.environ.get("DEBUG", "false")) # False
54
+ PORT = parse_int(os.environ.get("PORT", "8080")) # 8080
55
+ HOSTS = parse_list(os.environ.get("ALLOWED_HOSTS", "")) # []
56
+
57
+ # With defaults
58
+ parse_bool("maybe", default=False) # False — no exception
59
+ parse_int("oops", default=0) # 0
60
+
61
+ # Durations
62
+ from datetime import timedelta
63
+ parse_duration("2h30m") # timedelta(hours=2, minutes=30)
64
+ parse_duration("1w2d") # timedelta(weeks=1, days=2)
65
+ ```
66
+
67
+ ## API
68
+
69
+ ### `parse_bool(s, *, default=<raise>)`
70
+
71
+ | Input | Result |
72
+ |-------|--------|
73
+ | `"1"`, `"true"`, `"yes"`, `"on"`, `"t"`, `"y"` | `True` |
74
+ | `"0"`, `"false"`, `"no"`, `"off"`, `"f"`, `"n"` | `False` |
75
+ | anything else (no default) | `ParseError` |
76
+ | anything else (default given) | `default` |
77
+
78
+ Case-insensitive. Strips surrounding whitespace.
79
+
80
+ ### `parse_int(s, *, default=<raise>, base=10)`
81
+
82
+ ```python
83
+ parse_int("42") # 42
84
+ parse_int("0xff", base=16) # 255
85
+ parse_int("bad", default=0) # 0
86
+ ```
87
+
88
+ ### `parse_float(s, *, default=<raise>)`
89
+
90
+ ```python
91
+ parse_float("3.14") # 3.14
92
+ parse_float("1e-3") # 0.001
93
+ parse_float("bad", default=0) # 0
94
+ ```
95
+
96
+ ### `parse_list(s, sep=",", *, strip=True)`
97
+
98
+ ```python
99
+ parse_list("a, b, c") # ["a", "b", "c"]
100
+ parse_list("a|b|c", sep="|") # ["a", "b", "c"]
101
+ parse_list("") # []
102
+ ```
103
+
104
+ ### `parse_duration(s)`
105
+
106
+ Parses combinations of `Nw Nd Nh Nm Ns` (weeks/days/hours/minutes/seconds).
107
+
108
+ ```python
109
+ parse_duration("30s") # timedelta(seconds=30)
110
+ parse_duration("5m") # timedelta(minutes=5)
111
+ parse_duration("2h30m") # timedelta(hours=2, minutes=30)
112
+ parse_duration("1w2d3h4m5s") # timedelta(weeks=1, days=2, hours=3, minutes=4, seconds=5)
113
+ ```
114
+
115
+ ## Error handling
116
+
117
+ All functions raise `ParseError` (subclass of `ValueError`) when input is invalid and no
118
+ default is given.
119
+
120
+ ```python
121
+ from strcoerce import ParseError
122
+
123
+ try:
124
+ val = parse_bool(user_input)
125
+ except ParseError as e:
126
+ print(f"Invalid boolean: {e}")
127
+ ```
128
+
129
+ ## License
130
+
131
+ MIT
@@ -0,0 +1,6 @@
1
+ strcoerce/__init__.py,sha256=qIF24CXaZk1-qEedC2oSFHhaSGdLzjaT4x4T9ahc1OY,281
2
+ strcoerce/_core.py,sha256=F9dFzm-P1kvcPNChftNs3vq8dk_-nc14YOgIpJCGjDA,3615
3
+ strcoerce-0.1.0.dist-info/METADATA,sha256=QE5cO17gCVbWVGMIaQSnmDYcWa-F6Fcg56pv8FCiLD4,3637
4
+ strcoerce-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ strcoerce-0.1.0.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
6
+ strcoerce-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.