strcoerce 0.1.0__tar.gz
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-0.1.0/.github/workflows/ci.yml +20 -0
- strcoerce-0.1.0/.github/workflows/publish.yml +21 -0
- strcoerce-0.1.0/.gitignore +8 -0
- strcoerce-0.1.0/CHANGELOG.md +11 -0
- strcoerce-0.1.0/LICENSE +21 -0
- strcoerce-0.1.0/PKG-INFO +131 -0
- strcoerce-0.1.0/README.md +107 -0
- strcoerce-0.1.0/pyproject.toml +50 -0
- strcoerce-0.1.0/src/strcoerce/__init__.py +18 -0
- strcoerce-0.1.0/src/strcoerce/_core.py +111 -0
- strcoerce-0.1.0/tests/test_core.py +184 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e ".[dev]" || pip install -e . pytest pytest-cov
|
|
20
|
+
- run: pytest
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
publish:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
environment: pypi
|
|
12
|
+
permissions:
|
|
13
|
+
id-token: write # required for trusted publishing
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.12"
|
|
19
|
+
- run: pip install build
|
|
20
|
+
- run: python -m build
|
|
21
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
- Initial release
|
|
6
|
+
- `parse_bool`: handles true/false/yes/no/1/0/on/off (case-insensitive)
|
|
7
|
+
- `parse_int`: with optional base parameter for hex/binary
|
|
8
|
+
- `parse_float`: with scientific notation support
|
|
9
|
+
- `parse_list`: delimited string to list with configurable separator and strip
|
|
10
|
+
- `parse_duration`: compact duration strings to `timedelta` (Nw Nd Nh Nm Ns)
|
|
11
|
+
- `ParseError`: subclass of `ValueError` for clean exception handling
|
strcoerce-0.1.0/LICENSE
ADDED
|
@@ -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.
|
strcoerce-0.1.0/PKG-INFO
ADDED
|
@@ -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,107 @@
|
|
|
1
|
+
# strcoerce
|
|
2
|
+
|
|
3
|
+
Safe string-to-type coercion for Python. Zero dependencies.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
import os
|
|
9
|
+
DEBUG = bool(os.environ.get("DEBUG", "false")) # Always True — "false" is a non-empty string
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`bool("false")` is `True` in Python. This catches experienced developers off guard and is a
|
|
13
|
+
[documented trap](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) with no
|
|
14
|
+
stdlib fix.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
pip install strcoerce
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from strcoerce import parse_bool, parse_int, parse_float, parse_list, parse_duration
|
|
27
|
+
|
|
28
|
+
# Environment variables
|
|
29
|
+
DEBUG = parse_bool(os.environ.get("DEBUG", "false")) # False
|
|
30
|
+
PORT = parse_int(os.environ.get("PORT", "8080")) # 8080
|
|
31
|
+
HOSTS = parse_list(os.environ.get("ALLOWED_HOSTS", "")) # []
|
|
32
|
+
|
|
33
|
+
# With defaults
|
|
34
|
+
parse_bool("maybe", default=False) # False — no exception
|
|
35
|
+
parse_int("oops", default=0) # 0
|
|
36
|
+
|
|
37
|
+
# Durations
|
|
38
|
+
from datetime import timedelta
|
|
39
|
+
parse_duration("2h30m") # timedelta(hours=2, minutes=30)
|
|
40
|
+
parse_duration("1w2d") # timedelta(weeks=1, days=2)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
### `parse_bool(s, *, default=<raise>)`
|
|
46
|
+
|
|
47
|
+
| Input | Result |
|
|
48
|
+
|-------|--------|
|
|
49
|
+
| `"1"`, `"true"`, `"yes"`, `"on"`, `"t"`, `"y"` | `True` |
|
|
50
|
+
| `"0"`, `"false"`, `"no"`, `"off"`, `"f"`, `"n"` | `False` |
|
|
51
|
+
| anything else (no default) | `ParseError` |
|
|
52
|
+
| anything else (default given) | `default` |
|
|
53
|
+
|
|
54
|
+
Case-insensitive. Strips surrounding whitespace.
|
|
55
|
+
|
|
56
|
+
### `parse_int(s, *, default=<raise>, base=10)`
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
parse_int("42") # 42
|
|
60
|
+
parse_int("0xff", base=16) # 255
|
|
61
|
+
parse_int("bad", default=0) # 0
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### `parse_float(s, *, default=<raise>)`
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
parse_float("3.14") # 3.14
|
|
68
|
+
parse_float("1e-3") # 0.001
|
|
69
|
+
parse_float("bad", default=0) # 0
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### `parse_list(s, sep=",", *, strip=True)`
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
parse_list("a, b, c") # ["a", "b", "c"]
|
|
76
|
+
parse_list("a|b|c", sep="|") # ["a", "b", "c"]
|
|
77
|
+
parse_list("") # []
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### `parse_duration(s)`
|
|
81
|
+
|
|
82
|
+
Parses combinations of `Nw Nd Nh Nm Ns` (weeks/days/hours/minutes/seconds).
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
parse_duration("30s") # timedelta(seconds=30)
|
|
86
|
+
parse_duration("5m") # timedelta(minutes=5)
|
|
87
|
+
parse_duration("2h30m") # timedelta(hours=2, minutes=30)
|
|
88
|
+
parse_duration("1w2d3h4m5s") # timedelta(weeks=1, days=2, hours=3, minutes=4, seconds=5)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Error handling
|
|
92
|
+
|
|
93
|
+
All functions raise `ParseError` (subclass of `ValueError`) when input is invalid and no
|
|
94
|
+
default is given.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from strcoerce import ParseError
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
val = parse_bool(user_input)
|
|
101
|
+
except ParseError as e:
|
|
102
|
+
print(f"Invalid boolean: {e}")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "strcoerce"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Safe string-to-type coercion — parse_bool, parse_int, parse_float, parse_list, parse_duration"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
keywords = ["parse", "bool", "coerce", "string", "type", "convert", "environment"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.9",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Utilities",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/SpinnakerSix/strcoerce"
|
|
29
|
+
Issues = "https://github.com/SpinnakerSix/strcoerce/issues"
|
|
30
|
+
Changelog = "https://github.com/SpinnakerSix/strcoerce/blob/main/CHANGELOG.md"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/strcoerce"]
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = [
|
|
37
|
+
"pytest>=7",
|
|
38
|
+
"pytest-cov>=4",
|
|
39
|
+
"ruff>=0.4",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[tool.pytest.ini_options]
|
|
43
|
+
testpaths = ["tests"]
|
|
44
|
+
addopts = "--cov=strcoerce --cov-report=term-missing -v"
|
|
45
|
+
|
|
46
|
+
[tool.coverage.run]
|
|
47
|
+
source = ["src"]
|
|
48
|
+
|
|
49
|
+
[tool.ruff.lint]
|
|
50
|
+
select = ["E", "F", "I", "UP"]
|
|
@@ -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
|
+
]
|
|
@@ -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,184 @@
|
|
|
1
|
+
from datetime import timedelta
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from strcoerce import ParseError, parse_bool, parse_duration, parse_float, parse_int, parse_list
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestParseBool:
|
|
9
|
+
@pytest.mark.parametrize("s", ["1", "true", "True", "TRUE", "yes", "YES", "on", "ON", "t", "y"])
|
|
10
|
+
def test_true_values(self, s):
|
|
11
|
+
assert parse_bool(s) is True
|
|
12
|
+
|
|
13
|
+
@pytest.mark.parametrize("s", ["0", "false", "False", "FALSE", "no", "NO", "off", "OFF", "f", "n"])
|
|
14
|
+
def test_false_values(self, s):
|
|
15
|
+
assert parse_bool(s) is False
|
|
16
|
+
|
|
17
|
+
def test_strips_whitespace(self):
|
|
18
|
+
assert parse_bool(" true ") is True
|
|
19
|
+
assert parse_bool(" false ") is False
|
|
20
|
+
|
|
21
|
+
def test_python_bool_trap(self):
|
|
22
|
+
# The whole reason this library exists
|
|
23
|
+
assert parse_bool("false") is False # bool("false") would be True
|
|
24
|
+
assert parse_bool("0") is False # bool("0") would be True
|
|
25
|
+
assert parse_bool("no") is False
|
|
26
|
+
|
|
27
|
+
def test_invalid_raises_parse_error(self):
|
|
28
|
+
with pytest.raises(ParseError):
|
|
29
|
+
parse_bool("maybe")
|
|
30
|
+
|
|
31
|
+
def test_parse_error_is_value_error(self):
|
|
32
|
+
with pytest.raises(ValueError):
|
|
33
|
+
parse_bool("maybe")
|
|
34
|
+
|
|
35
|
+
def test_default_returned_on_invalid(self):
|
|
36
|
+
assert parse_bool("maybe", default=False) is False
|
|
37
|
+
assert parse_bool("maybe", default=True) is True
|
|
38
|
+
|
|
39
|
+
def test_wrong_type_raises_type_error(self):
|
|
40
|
+
with pytest.raises(TypeError):
|
|
41
|
+
parse_bool(True)
|
|
42
|
+
with pytest.raises(TypeError):
|
|
43
|
+
parse_bool(1)
|
|
44
|
+
with pytest.raises(TypeError):
|
|
45
|
+
parse_bool(None)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TestParseInt:
|
|
49
|
+
def test_basic(self):
|
|
50
|
+
assert parse_int("42") == 42
|
|
51
|
+
assert parse_int("-1") == -1
|
|
52
|
+
assert parse_int("0") == 0
|
|
53
|
+
|
|
54
|
+
def test_strips_whitespace(self):
|
|
55
|
+
assert parse_int(" 42 ") == 42
|
|
56
|
+
|
|
57
|
+
def test_hex(self):
|
|
58
|
+
assert parse_int("ff", base=16) == 255
|
|
59
|
+
assert parse_int("0xff", base=16) == 255
|
|
60
|
+
assert parse_int("FF", base=16) == 255
|
|
61
|
+
|
|
62
|
+
def test_binary(self):
|
|
63
|
+
assert parse_int("1010", base=2) == 10
|
|
64
|
+
|
|
65
|
+
def test_invalid_raises(self):
|
|
66
|
+
with pytest.raises(ParseError):
|
|
67
|
+
parse_int("abc")
|
|
68
|
+
with pytest.raises(ParseError):
|
|
69
|
+
parse_int("3.14")
|
|
70
|
+
|
|
71
|
+
def test_default_on_invalid(self):
|
|
72
|
+
assert parse_int("abc", default=0) == 0
|
|
73
|
+
assert parse_int("", default=-1) == -1
|
|
74
|
+
|
|
75
|
+
def test_wrong_type_raises(self):
|
|
76
|
+
with pytest.raises(TypeError):
|
|
77
|
+
parse_int(42)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class TestParseFloat:
|
|
81
|
+
def test_basic(self):
|
|
82
|
+
assert parse_float("3.14") == pytest.approx(3.14)
|
|
83
|
+
assert parse_float("-2.5") == pytest.approx(-2.5)
|
|
84
|
+
assert parse_float("0") == pytest.approx(0.0)
|
|
85
|
+
|
|
86
|
+
def test_scientific_notation(self):
|
|
87
|
+
assert parse_float("1e10") == pytest.approx(1e10)
|
|
88
|
+
assert parse_float("1.5E-3") == pytest.approx(0.0015)
|
|
89
|
+
|
|
90
|
+
def test_integer_string(self):
|
|
91
|
+
assert parse_float("42") == pytest.approx(42.0)
|
|
92
|
+
|
|
93
|
+
def test_strips_whitespace(self):
|
|
94
|
+
assert parse_float(" 3.14 ") == pytest.approx(3.14)
|
|
95
|
+
|
|
96
|
+
def test_invalid_raises(self):
|
|
97
|
+
with pytest.raises(ParseError):
|
|
98
|
+
parse_float("not_a_float")
|
|
99
|
+
with pytest.raises(ParseError):
|
|
100
|
+
parse_float("")
|
|
101
|
+
|
|
102
|
+
def test_default_on_invalid(self):
|
|
103
|
+
assert parse_float("bad", default=0.0) == 0.0
|
|
104
|
+
|
|
105
|
+
def test_wrong_type_raises(self):
|
|
106
|
+
with pytest.raises(TypeError):
|
|
107
|
+
parse_float(3.14)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class TestParseList:
|
|
111
|
+
def test_basic(self):
|
|
112
|
+
assert parse_list("a,b,c") == ["a", "b", "c"]
|
|
113
|
+
|
|
114
|
+
def test_strips_whitespace_by_default(self):
|
|
115
|
+
assert parse_list("a, b, c") == ["a", "b", "c"]
|
|
116
|
+
assert parse_list(" a , b ") == ["a", "b"]
|
|
117
|
+
|
|
118
|
+
def test_no_strip(self):
|
|
119
|
+
assert parse_list("a, b, c", strip=False) == ["a", " b", " c"]
|
|
120
|
+
|
|
121
|
+
def test_custom_separator(self):
|
|
122
|
+
assert parse_list("a|b|c", sep="|") == ["a", "b", "c"]
|
|
123
|
+
assert parse_list("a::b::c", sep="::") == ["a", "b", "c"]
|
|
124
|
+
|
|
125
|
+
def test_empty_string_returns_empty_list(self):
|
|
126
|
+
assert parse_list("") == []
|
|
127
|
+
assert parse_list(" ") == []
|
|
128
|
+
|
|
129
|
+
def test_filters_empty_items(self):
|
|
130
|
+
assert parse_list("a,,b") == ["a", "b"]
|
|
131
|
+
assert parse_list(",a,") == ["a"]
|
|
132
|
+
|
|
133
|
+
def test_single_item(self):
|
|
134
|
+
assert parse_list("only") == ["only"]
|
|
135
|
+
|
|
136
|
+
def test_newline_separator(self):
|
|
137
|
+
assert parse_list("a\nb\nc", sep="\n") == ["a", "b", "c"]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class TestParseDuration:
|
|
141
|
+
def test_seconds(self):
|
|
142
|
+
assert parse_duration("30s") == timedelta(seconds=30)
|
|
143
|
+
assert parse_duration("1s") == timedelta(seconds=1)
|
|
144
|
+
|
|
145
|
+
def test_minutes(self):
|
|
146
|
+
assert parse_duration("5m") == timedelta(minutes=5)
|
|
147
|
+
|
|
148
|
+
def test_hours(self):
|
|
149
|
+
assert parse_duration("2h") == timedelta(hours=2)
|
|
150
|
+
|
|
151
|
+
def test_days(self):
|
|
152
|
+
assert parse_duration("3d") == timedelta(days=3)
|
|
153
|
+
|
|
154
|
+
def test_weeks(self):
|
|
155
|
+
assert parse_duration("1w") == timedelta(weeks=1)
|
|
156
|
+
|
|
157
|
+
def test_combined(self):
|
|
158
|
+
assert parse_duration("2h30m") == timedelta(hours=2, minutes=30)
|
|
159
|
+
assert parse_duration("1d12h") == timedelta(days=1, hours=12)
|
|
160
|
+
assert parse_duration("1w2d3h4m5s") == timedelta(
|
|
161
|
+
weeks=1, days=2, hours=3, minutes=4, seconds=5
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def test_strips_whitespace(self):
|
|
165
|
+
assert parse_duration(" 5m ") == timedelta(minutes=5)
|
|
166
|
+
|
|
167
|
+
def test_case_insensitive(self):
|
|
168
|
+
assert parse_duration("5M") == timedelta(minutes=5)
|
|
169
|
+
assert parse_duration("2H") == timedelta(hours=2)
|
|
170
|
+
assert parse_duration("1W") == timedelta(weeks=1)
|
|
171
|
+
|
|
172
|
+
def test_empty_raises(self):
|
|
173
|
+
with pytest.raises(ParseError):
|
|
174
|
+
parse_duration("")
|
|
175
|
+
with pytest.raises(ParseError):
|
|
176
|
+
parse_duration(" ")
|
|
177
|
+
|
|
178
|
+
def test_invalid_raises(self):
|
|
179
|
+
with pytest.raises(ParseError):
|
|
180
|
+
parse_duration("foobar")
|
|
181
|
+
with pytest.raises(ParseError):
|
|
182
|
+
parse_duration("5x")
|
|
183
|
+
with pytest.raises(ParseError):
|
|
184
|
+
parse_duration("5") # number with no unit
|