format-input 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.
@@ -0,0 +1,3 @@
1
+ from .format_input import format_input
2
+
3
+ __all__ = ["format_input"]
@@ -0,0 +1,62 @@
1
+ import typing
2
+ import re
3
+ import sys
4
+ from .helpers import *
5
+ from .handlers import *
6
+ from collections import deque
7
+
8
+ NAME_PREFIX = r"(?<![a-z_:])[a-z_]+:"
9
+ RE_NEW_LINE = re.compile(r";(?![^[\]]*\])")
10
+ RE_LINE_MATCH = re.compile(
11
+ rf"{NAME_PREFIX}(?P<named_type_greedy>str\*)(?![\w*])" # t:str*
12
+ rf"|{NAME_PREFIX}(?P<named_type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # n:int[5] f:float[7] t:str[1]
13
+ rf"|{NAME_PREFIX}(?P<named_type_list>(?:int|str|float)\[\])(?![\w\[])" # n:int[] f:float[] t:str[]
14
+ rf"|{NAME_PREFIX}(?P<named_type>(?:int|str|float))\b" # n:int f:float t:str
15
+ r"|\b(?P<type_greedy>str\*)(?![\w*])" # str*
16
+ r"|\b(?P<type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # int[5] float[7] str[1]
17
+ r"|\b(?P<type_list>(?:int|str|float)\[\])(?![\w\[])" # int[] float[] str[]
18
+ r"|\b(?P<type>int|str|float)\b" # int float str
19
+ )
20
+
21
+
22
+ def readline(stream: typing.TextIO) -> str:
23
+ line = stream.readline()
24
+ if line == "": return EOFError
25
+ return line.rstrip("\r\n")
26
+
27
+
28
+ def format_input(spec: str, stream: typing.TextIO | None = None, named_variables: bool = False) -> list[typing.Any] | dict[str, typing.Any]:
29
+ if stream is None: stream = sys.stdin
30
+
31
+ output = {} if named_variables else []
32
+ inp_queue: deque[str] = deque()
33
+ lines = RE_NEW_LINE.split(spec)
34
+
35
+ for line in lines:
36
+ inp = readline(stream)
37
+ inps = inp.split(" ")
38
+ inp_queue.clear()
39
+ inp_queue.extend(inps)
40
+
41
+ for m in RE_LINE_MATCH.finditer(line):
42
+
43
+ match (m.lastgroup):
44
+ case "named_type_greedy": ret = handle_named_type_greedy(m.group(), inp_queue)
45
+ case "type_greedy": ret = handle_type_greedy(inp_queue)
46
+ case "named_type_len_list": ret = handle_named_type_list(m.group(), inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
47
+ case "type_len_list": ret = handle_type_list(m.group(), inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
48
+ case "named_type_list": ret = handle_named_type_list(m.group(), inp_queue, max_size=-1)
49
+ case "type_list": ret = handle_type_list(m.group(), inp_queue, max_size=-1)
50
+ case "named_type": ret = handle_named_type(m.group(), inp_queue)
51
+ case "type": ret = handle_type(m.group(), inp_queue)
52
+
53
+ if isinstance(ret, dict) and not named_variables:
54
+ output.extend([ v for v in ret.values() ])
55
+ elif isinstance(ret, dict) and named_variables:
56
+ output.update(ret)
57
+ elif not isinstance(ret, dict) and not named_variables:
58
+ output.append(ret)
59
+ else:
60
+ raise TypeError("Cannot add an unnamed value to named_variables=True")
61
+
62
+ return output
@@ -0,0 +1,146 @@
1
+ from collections import deque
2
+ from .helpers import *
3
+
4
+ def handle_named_type_greedy(dt: str, q: deque[str]) -> str:
5
+ var, _ = dt.split(":")
6
+ output = {var: []}
7
+
8
+ while len(q) > 0:
9
+ inp = q.popleft()
10
+ if is_str(inp):
11
+ output[var].append(inp)
12
+ else:
13
+ q.appendleft(inp) # Not a string, return it back to the queue and return
14
+ break
15
+
16
+ output[var] = " ".join(output[var])
17
+ return output
18
+
19
+ def handle_type_greedy(q: deque[str]) -> str:
20
+ output = []
21
+
22
+ while len(q) > 0:
23
+ inp = q.popleft()
24
+ if is_str(inp):
25
+ output.append(inp)
26
+ else:
27
+ q.appendleft(inp) # Not a string, return it back to the queue and return
28
+ break
29
+
30
+ return " ".join(output)
31
+
32
+ def handle_named_type_list(dt: str, q: deque[str], max_size = -1) -> dict[str, list[str]] | dict[str, list[int]] | dict[str, list[float]]:
33
+ size_left = max_size
34
+ var, dt = dt.split(":")
35
+ output = {var: []}
36
+
37
+ match (dt):
38
+ case dt if dt.startswith("str"):
39
+ while len(q) > 0 and size_left != 0:
40
+ inp = q.popleft()
41
+ if is_str(inp):
42
+ output[var].append(inp)
43
+ size_left -= 1
44
+ else:
45
+ q.appendleft(inp) # Not a string, return it back to the queue and return
46
+ break
47
+
48
+ return output
49
+
50
+ case dt if dt.startswith("int"):
51
+ while len(q) > 0 and size_left != 0:
52
+ inp = q.popleft()
53
+ if is_int(inp):
54
+ output[var].append(int(inp))
55
+ size_left -= 1
56
+ else:
57
+ q.appendleft(inp) # Not an int, return it back to the queue and return
58
+ break
59
+
60
+ return output
61
+
62
+ case dt if dt.startswith("float"):
63
+ while len(q) > 0 and size_left != 0:
64
+ inp = q.popleft()
65
+ if is_float(inp):
66
+ output[var].append(float(inp))
67
+ size_left -= 1
68
+ else:
69
+ q.appendleft(inp) # Not a float, return it back to the queue and return
70
+ break
71
+
72
+ return output
73
+
74
+ def handle_type_list(dt: str, q: deque[str], max_size = -1) -> list[str] | list[int] | list[float]:
75
+ size_left = max_size
76
+ output = []
77
+
78
+ match (dt):
79
+ case dt if dt.startswith("str"):
80
+ while len(q) > 0 and size_left != 0:
81
+ inp = q.popleft()
82
+ if is_str(inp):
83
+ output.append(inp)
84
+ size_left -= 1
85
+ else:
86
+ q.appendleft(inp) # Not a string, return it back to the queue and return
87
+ break
88
+
89
+ return output
90
+
91
+ case dt if dt.startswith("int"):
92
+ while len(q) > 0 and size_left != 0:
93
+ inp = q.popleft()
94
+ if is_int(inp):
95
+ output.append(int(inp))
96
+ size_left -= 1
97
+ else:
98
+ q.appendleft(inp) # Not an int, return it back to the queue and return
99
+ break
100
+
101
+ return output
102
+
103
+ case dt if dt.startswith("float"):
104
+ while len(q) > 0 and size_left != 0:
105
+ inp = q.popleft()
106
+ if is_float(inp):
107
+ output.append(float(inp))
108
+ size_left -= 1
109
+ else:
110
+ q.appendleft(inp) # Not a float, return it back to the queue and return
111
+ break
112
+
113
+ return output
114
+
115
+ def handle_named_type(dt: str, q: deque[str]) -> dict[str, str] | dict[str, int] | dict[str, float] | dict[str, None]:
116
+ inp = q.popleft()
117
+ var, dt = dt.split(":")
118
+
119
+ match (dt):
120
+ case "str": return {var: str(inp)}
121
+ case "int":
122
+ try:
123
+ return {var: int(inp)}
124
+ except ValueError:
125
+ return {var: None}
126
+ case "float":
127
+ try:
128
+ return {var: float(inp)}
129
+ except ValueError:
130
+ return {var: None}
131
+
132
+ def handle_type(dt: str, q: deque[str]) -> str | int | float | None:
133
+ inp = q.popleft()
134
+
135
+ match (dt):
136
+ case "str": return str(inp)
137
+ case "int":
138
+ try:
139
+ return int(inp)
140
+ except ValueError:
141
+ return None
142
+ case "float":
143
+ try:
144
+ return float(inp)
145
+ except ValueError:
146
+ return None
@@ -0,0 +1,19 @@
1
+ import math
2
+
3
+ def is_str(val: str) -> bool:
4
+ return not (is_int(val) or is_float(val))
5
+
6
+ def is_int(val: str) -> bool:
7
+ try:
8
+ int(val)
9
+ return True
10
+ except ValueError:
11
+ return False
12
+
13
+ def is_float(val: str) -> bool:
14
+ try:
15
+ num = float(val)
16
+ if not math.isnan(num) and not math.isinf(num):
17
+ return True
18
+ except ValueError:
19
+ return False
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: format_input
3
+ Version: 0.1.0
4
+ Summary: A Python library for dynamically formatting and processing input
5
+ Author-email: GabbaTK <gabiteok+pypi@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/GabbaTK/Format-Input/
8
+ Project-URL: Issues, https://github.com/GabbaTK/Format-Input/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # Format Input
17
+
18
+ `Format Input` is a small Python library for parsing console or text-stream input
19
+ according to a compact format specification. Instead of repeatedly calling
20
+ `input()`, splitting strings, and converting values by hand, describe the shape
21
+ of each input line once and receive typed Python values.
22
+
23
+ It is useful for:
24
+
25
+ - Competitive programming problems with predictable, line-based input.
26
+ - Command-line tools that read structured text.
27
+ - Small scripts that need to convert input into integers, floats, and strings.
28
+ - Situations where input may contain a mixture of scalar values, lists, and
29
+ values followed by free-form text.
30
+
31
+ For example, instead of manually splitting and converting a line:
32
+
33
+ ```python
34
+ parts = input().split()
35
+ count = int(parts[0])
36
+ ratio = float(parts[1])
37
+ name = parts[2]
38
+ ```
39
+
40
+ You can describe the input once and receive typed values directly:
41
+
42
+ ```python
43
+ count, ratio, name = format_input("int float str")
44
+ ```
45
+
46
+ See [USAGE.MD](./USAGE.MD) for all supported types and format specifications.
47
+
48
+ ## Requirements
49
+
50
+ - Python 3.10 or newer
51
+ - No third-party dependencies
52
+
53
+ ## Installation
54
+
55
+ Clone the repository:
56
+
57
+ ```bash
58
+ git clone https://github.com/GabbaTK/Format-Input.git
59
+ cd Format-Input
60
+ ```
61
+
62
+ The package is stored in `src/`. To run the test suite from the repository root:
63
+
64
+ ```bash
65
+ PYTHONPATH=src python -m unittest discover -s tests -v
66
+ ```
67
+
68
+ ## License
69
+
70
+ This project is available under the [MIT License](./LICENSE).
71
+
72
+ ## AI disclosure
73
+
74
+ No AI was used in the making of the code.
@@ -0,0 +1,9 @@
1
+ format_input/__init__.py,sha256=v2bpW2T2kdwOQHTn7dx_gramJvH1l68ml3AFbgUhwe0,66
2
+ format_input/format_input.py,sha256=v1JPRdwfiODEjxGH62hIIS3fuN4_LdfX_60wtszriXM,3079
3
+ format_input/handlers.py,sha256=3h-VheYgKnMhIMZOVln3qAmkcgvwU8S2yqV7SeFbn4k,4542
4
+ format_input/helpers.py,sha256=kr4UDYhJCUcZds5E_g9PHYE54Wp1fAWku9XcgZIHhGI,401
5
+ format_input-0.1.0.dist-info/licenses/LICENSE,sha256=aCyUKLb8_s2FsNJjrUWM9r0WtSGrxPMZWof5uhQnyCM,1062
6
+ format_input-0.1.0.dist-info/METADATA,sha256=zR_iRn_mU2bbUBX9-EkAS2CW25jCjCUTTsX_zx5Spyw,2040
7
+ format_input-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ format_input-0.1.0.dist-info/top_level.txt,sha256=QJCf0fpy2_yXpS5nhwtRDK0uhf5vP_jNHJoc8SrfvJo,13
9
+ format_input-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gabba
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.
@@ -0,0 +1 @@
1
+ format_input