format-input 0.2.0__tar.gz → 0.4.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.
Files changed (27) hide show
  1. format_input-0.4.0/PKG-INFO +87 -0
  2. format_input-0.4.0/README.MD +71 -0
  3. {format_input-0.2.0 → format_input-0.4.0}/pyproject.toml +5 -2
  4. format_input-0.4.0/src/format_input/format_input.py +106 -0
  5. {format_input-0.2.0 → format_input-0.4.0}/src/format_input/handlers.py +16 -0
  6. {format_input-0.2.0 → format_input-0.4.0}/src/format_input/helpers.py +6 -0
  7. format_input-0.4.0/src/format_input.egg-info/PKG-INFO +87 -0
  8. {format_input-0.2.0 → format_input-0.4.0}/src/format_input.egg-info/SOURCES.txt +4 -0
  9. format_input-0.4.0/src/format_input.egg-info/requires.txt +1 -0
  10. {format_input-0.2.0 → format_input-0.4.0}/tests/test_000_edgecase.py +48 -0
  11. format_input-0.4.0/tests/test_g_groups.py +170 -0
  12. format_input-0.4.0/tests/test_h_times_group.py +110 -0
  13. format_input-0.2.0/PKG-INFO +0 -14
  14. format_input-0.2.0/src/format_input/format_input.py +0 -73
  15. format_input-0.2.0/src/format_input.egg-info/PKG-INFO +0 -14
  16. {format_input-0.2.0 → format_input-0.4.0}/LICENSE +0 -0
  17. {format_input-0.2.0 → format_input-0.4.0}/setup.cfg +0 -0
  18. {format_input-0.2.0 → format_input-0.4.0}/src/format_input/__init__.py +0 -0
  19. {format_input-0.2.0 → format_input-0.4.0}/src/format_input.egg-info/dependency_links.txt +0 -0
  20. {format_input-0.2.0 → format_input-0.4.0}/src/format_input.egg-info/top_level.txt +0 -0
  21. {format_input-0.2.0 → format_input-0.4.0}/tests/test_a_basic_dtype.py +0 -0
  22. {format_input-0.2.0 → format_input-0.4.0}/tests/test_b_basic_dtype_list.py +0 -0
  23. {format_input-0.2.0 → format_input-0.4.0}/tests/test_c_basic_dtype_list_len.py +0 -0
  24. {format_input-0.2.0 → format_input-0.4.0}/tests/test_d_basic_dtype_greedy.py +0 -0
  25. {format_input-0.2.0 → format_input-0.4.0}/tests/test_e_named_dtype.py +0 -0
  26. {format_input-0.2.0 → format_input-0.4.0}/tests/test_f_extra.py +0 -0
  27. {format_input-0.2.0 → format_input-0.4.0}/tests/test_mix_abcd.py +0 -0
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: format-input
3
+ Version: 0.4.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
+ Requires-Dist: regex>=2026.1.15
15
+ Dynamic: license-file
16
+
17
+ # Format Input
18
+ ![PyPI Downloads](https://img.shields.io/pypi/dm/format-input) ![Test Count](https://img.shields.io/badge/tests-212-brightgreen)
19
+
20
+ `Format Input` is a small Python library for parsing console or text-stream input
21
+ according to a compact format specification. Instead of repeatedly calling
22
+ `input()`, splitting strings, and converting values by hand, describe the shape
23
+ of each input line once and receive typed Python values.
24
+
25
+ It is useful for:
26
+
27
+ - Competitive programming problems with predictable, line-based input.
28
+ - Command-line tools that read structured text.
29
+ - Small scripts that need to convert input into integers, floats, and strings.
30
+ - Situations where input may contain a mixture of scalar values, lists, and
31
+ values followed by free-form text.
32
+
33
+ For example, instead of manually splitting and converting a line:
34
+
35
+ ```python
36
+ parts = input().split()
37
+ count = int(parts[0])
38
+ ratio = float(parts[1])
39
+ name = parts[2]
40
+ ```
41
+
42
+ You can describe the input once and receive typed values directly:
43
+
44
+ ```python
45
+ count, ratio, name = format_input("int float str")
46
+ ```
47
+
48
+ See [USAGE.MD](./USAGE.MD) for all supported types and format specifications.
49
+
50
+ ## Requirements
51
+
52
+ - Python 3.10 or newer
53
+ - `regex` 2026.1.15 or newer
54
+
55
+ ## Installation
56
+
57
+ Install the published package from PyPI:
58
+
59
+ ```bash
60
+ pip install format-input
61
+ ```
62
+
63
+ Or clone the repository and install it manually:
64
+
65
+ Clone the repository:
66
+
67
+ ```bash
68
+ git clone https://github.com/GabbaTK/Format-Input.git
69
+ cd Format-Input
70
+ ```
71
+
72
+ The package is stored in `src/`.
73
+
74
+
75
+ To run the test suite from the repository root:
76
+
77
+ ```bash
78
+ PYTHONPATH=src python -m unittest discover -s tests -v
79
+ ```
80
+
81
+ ## License
82
+
83
+ This project is available under the [MIT License](./LICENSE).
84
+
85
+ ## AI disclosure
86
+
87
+ No AI was used in the making of the code.
@@ -0,0 +1,71 @@
1
+ # Format Input
2
+ ![PyPI Downloads](https://img.shields.io/pypi/dm/format-input) ![Test Count](https://img.shields.io/badge/tests-212-brightgreen)
3
+
4
+ `Format Input` is a small Python library for parsing console or text-stream input
5
+ according to a compact format specification. Instead of repeatedly calling
6
+ `input()`, splitting strings, and converting values by hand, describe the shape
7
+ of each input line once and receive typed Python values.
8
+
9
+ It is useful for:
10
+
11
+ - Competitive programming problems with predictable, line-based input.
12
+ - Command-line tools that read structured text.
13
+ - Small scripts that need to convert input into integers, floats, and strings.
14
+ - Situations where input may contain a mixture of scalar values, lists, and
15
+ values followed by free-form text.
16
+
17
+ For example, instead of manually splitting and converting a line:
18
+
19
+ ```python
20
+ parts = input().split()
21
+ count = int(parts[0])
22
+ ratio = float(parts[1])
23
+ name = parts[2]
24
+ ```
25
+
26
+ You can describe the input once and receive typed values directly:
27
+
28
+ ```python
29
+ count, ratio, name = format_input("int float str")
30
+ ```
31
+
32
+ See [USAGE.MD](./USAGE.MD) for all supported types and format specifications.
33
+
34
+ ## Requirements
35
+
36
+ - Python 3.10 or newer
37
+ - `regex` 2026.1.15 or newer
38
+
39
+ ## Installation
40
+
41
+ Install the published package from PyPI:
42
+
43
+ ```bash
44
+ pip install format-input
45
+ ```
46
+
47
+ Or clone the repository and install it manually:
48
+
49
+ Clone the repository:
50
+
51
+ ```bash
52
+ git clone https://github.com/GabbaTK/Format-Input.git
53
+ cd Format-Input
54
+ ```
55
+
56
+ The package is stored in `src/`.
57
+
58
+
59
+ To run the test suite from the repository root:
60
+
61
+ ```bash
62
+ PYTHONPATH=src python -m unittest discover -s tests -v
63
+ ```
64
+
65
+ ## License
66
+
67
+ This project is available under the [MIT License](./LICENSE).
68
+
69
+ ## AI disclosure
70
+
71
+ No AI was used in the making of the code.
@@ -1,12 +1,15 @@
1
1
  [project]
2
2
  name = "format-input"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  authors = [
5
5
  { name="GabbaTK", email="gabiteok+pypi@gmail.com" },
6
6
  ]
7
7
  description = "A Python library for dynamically formatting and processing input"
8
- readme = "README.md"
8
+ readme = "README.MD"
9
9
  requires-python = ">=3.10"
10
+ dependencies = [
11
+ "regex>=2026.1.15",
12
+ ]
10
13
  classifiers = [
11
14
  "Programming Language :: Python :: 3",
12
15
  "Operating System :: OS Independent",
@@ -0,0 +1,106 @@
1
+ import typing
2
+ import regex as 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_NEW_LINE = re.compile(r";(?![^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*\])")
11
+ RE_LINE_MATCH = re.compile(
12
+ rf"{NAME_PREFIX}(?(DEFINE)(?P<named_inner>(?:[^\[\]]+|\[(?&named_inner)\])*))\[(?P<named_group>(?&named_inner))\]" # g:[ ... ]
13
+ rf"|{NAME_PREFIX}(?(DEFINE)(?P<named_times_inner>(?:[^\[\]]+|\[(?&named_times_inner)\])*))(?P<number>int|N|[a-z_]+|\d+)\s*\*\s*\[(?P<named_times_group>(?&named_times_inner))\]" # g:N*[ ... ]
14
+ r"|(?(DEFINE)(?P<inner>(?:[^\[\]]+|\[(?&inner)\])*))(?<=\[)(?P<group>(?&inner))(?=\])" # [ ... ]
15
+ r"|(?(DEFINE)(?P<times_inner>(?:[^\[\]]+|\[(?&times_inner)\])*))(?P<number>int|N|[a-z_]+|\d+)\s*\*\s*\[(?P<times_group>(?&times_inner))\]" # N*[ ... ]
16
+ rf"|{NAME_PREFIX}(?P<named_extra>\?)(?![\w?])" # e:?
17
+ rf"|{NAME_PREFIX}(?P<named_type_greedy>str\*)(?![\w*])" # t:str*
18
+ rf"|{NAME_PREFIX}(?P<named_type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # n:int[5] f:float[7] t:str[1]
19
+ rf"|{NAME_PREFIX}(?P<named_type_list>(?:int|str|float)\[\])(?![\w\[])" # n:int[] f:float[] t:str[]
20
+ rf"|{NAME_PREFIX}(?P<named_type>(?:int|str|float))\b" # n:int f:float t:str
21
+ r"|(?<![\w:])(?P<extra>\?)(?![\w?])" # ?
22
+ r"|\b(?P<type_greedy>str\*)(?![\w*])" # str*
23
+ r"|\b(?P<type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # int[5] float[7] str[1]
24
+ r"|\b(?P<type_list>(?:int|str|float)\[\])(?![\w\[])" # int[] float[] str[]
25
+ r"|\b(?P<type>int|str|float)\b" # int float str
26
+ )
27
+
28
+
29
+ def readline(stream: typing.TextIO) -> str:
30
+ line = stream.readline()
31
+ #if line == "": raise EOFError()
32
+ return line.rstrip("\r\n")
33
+
34
+
35
+ def format_input(spec: str, stream: typing.TextIO | None = None, named_variables: bool = False, shrink_output_in_times_group: bool = False, _input_queue: deque[str] | None = None, _times: str | int | None = None, _single_line_do_not_clear_queue: bool = False, _saved_vars: dict[str, typing.Any] | None = None) -> list[typing.Any] | dict[str, typing.Any]:
36
+ if stream is None: stream = sys.stdin
37
+
38
+ output = {} if named_variables else []
39
+ inp_queue: deque[str] = _input_queue if _input_queue is not None else deque()
40
+ variables = _saved_vars if _saved_vars is not None else {}
41
+ lines = RE_NEW_LINE.split(spec)
42
+
43
+ if _times:
44
+ if is_int(_times): num = int(_times)
45
+ else: num = handle_times(_times, inp_queue, lambda: readline(stream), variables)
46
+
47
+ t_out = []
48
+
49
+ if _times == "int": t_out.append(num)
50
+ for _ in range(num):
51
+ ret = format_input(spec, stream, named_variables=named_variables, _input_queue=inp_queue, _single_line_do_not_clear_queue=True, _saved_vars=variables)
52
+ # Instead of each iteration being in its own list if this flag is set allow them all to be in a single list if it only outputs a single element
53
+ if shrink_output_in_times_group and len(ret) == 1:
54
+ t_out.extend(ret)
55
+ else:
56
+ t_out.append(ret)
57
+
58
+ return t_out
59
+
60
+ for line in lines:
61
+ if len(inp_queue) == 0: # Always 0 unless _input_queue is provided then only during the first run is it not 0
62
+ inp = readline(stream)
63
+ inps = inp.split(" ")
64
+ inp_queue.extend(inps)
65
+
66
+ for m in RE_LINE_MATCH.finditer(line):
67
+ if "named" not in m.lastgroup and named_variables: raise TypeError("Cannot add an unnamed value when named_variables=True")
68
+
69
+ if "named" in m.lastgroup: var, dt = m.group().split(":", 1)
70
+ else: dt = m.group()
71
+
72
+ match (m.lastgroup):
73
+ case "times_group": ret = format_input(m.group("times_group"), stream, named_variables=named_variables, shrink_output_in_times_group=shrink_output_in_times_group, _input_queue=inp_queue, _times=m.group("number"), _saved_vars=variables)
74
+ case "named_group": ret = format_input(dt[1:-1], stream, named_variables=named_variables, _input_queue=inp_queue, _single_line_do_not_clear_queue=True, _saved_vars=variables) # Regex currently also includes the brackets in the match which are excess, so remove them here [1:-1] or fix the regex
75
+ case "group": ret = format_input(dt, stream, named_variables=named_variables, _input_queue=inp_queue, _single_line_do_not_clear_queue=True, _saved_vars=variables)
76
+ case "named_extra": ret = handle_extra(inp_queue)
77
+ case "extra": ret = handle_extra(inp_queue)
78
+ case "named_type_greedy": ret = handle_type_greedy(inp_queue)
79
+ case "type_greedy": ret = handle_type_greedy(inp_queue)
80
+ case "named_type_len_list": ret = handle_type_list(dt, inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
81
+ case "type_len_list": ret = handle_type_list(dt, inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
82
+ case "named_type_list": ret = handle_type_list(dt, inp_queue, max_size=-1)
83
+ case "type_list": ret = handle_type_list(dt, inp_queue, max_size=-1)
84
+ case "named_type": ret = handle_type(dt, inp_queue)
85
+ case "type": ret = handle_type(dt, inp_queue)
86
+
87
+ if "named" in m.lastgroup:
88
+ variables[var] = ret
89
+ ret = {var: ret}
90
+
91
+ if isinstance(ret, dict) and not named_variables:
92
+ output.extend([ v for v in ret.values() ])
93
+ elif isinstance(ret, dict) and named_variables:
94
+ output.update(ret)
95
+ elif not isinstance(ret, dict) and not named_variables and "times" in m.lastgroup:
96
+ output.extend(ret) # Unpack list to not nest lists when doing times group
97
+ elif not isinstance(ret, dict) and not named_variables:
98
+ output.append(ret)
99
+ else:
100
+ raise Exception("Unexpected error.")
101
+
102
+ # If there is a single line in the spec and the flag is set do not clear the queue
103
+ # Appped a ; to the end to manually clear the queue if you know there will be trailing data, otherwise do not
104
+ if not (_single_line_do_not_clear_queue and len(lines) == 1) and line.strip() != "": inp_queue.clear()
105
+
106
+ return output
@@ -1,6 +1,22 @@
1
+ import typing
1
2
  from collections import deque
2
3
  from .helpers import *
3
4
 
5
+ def handle_times(d: str, q: deque[str], read_stream: typing.Callable, var: dict[typing.Any]) -> int:
6
+ match (d):
7
+ case "int" | "N":
8
+ ret = read_queue_or_stream(q, read_stream)
9
+ if not is_int(ret): raise ValueError(f"Expected an integer, got {ret}")
10
+ return int(ret)
11
+ case _:
12
+ try:
13
+ val = var[d]
14
+ if not is_int(val): raise ValueError(f"Expected an integer, got {val}")
15
+ return int(val)
16
+ except IndexError as exc:
17
+ raise IndexError(f"No value found for variable '{d}'") from exc
18
+
19
+
4
20
  def handle_extra(q: deque[str]) -> str:
5
21
  output = []
6
22
 
@@ -1,4 +1,10 @@
1
1
  import math
2
+ import typing
3
+ from collections import deque
4
+
5
+ def read_queue_or_stream(q: deque[str], read_stream: typing.Callable) -> str:
6
+ if len(q) > 0: return q.popleft()
7
+ return read_stream()
2
8
 
3
9
  def not_empty(val: str):
4
10
  if val == "":
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: format-input
3
+ Version: 0.4.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
+ Requires-Dist: regex>=2026.1.15
15
+ Dynamic: license-file
16
+
17
+ # Format Input
18
+ ![PyPI Downloads](https://img.shields.io/pypi/dm/format-input) ![Test Count](https://img.shields.io/badge/tests-212-brightgreen)
19
+
20
+ `Format Input` is a small Python library for parsing console or text-stream input
21
+ according to a compact format specification. Instead of repeatedly calling
22
+ `input()`, splitting strings, and converting values by hand, describe the shape
23
+ of each input line once and receive typed Python values.
24
+
25
+ It is useful for:
26
+
27
+ - Competitive programming problems with predictable, line-based input.
28
+ - Command-line tools that read structured text.
29
+ - Small scripts that need to convert input into integers, floats, and strings.
30
+ - Situations where input may contain a mixture of scalar values, lists, and
31
+ values followed by free-form text.
32
+
33
+ For example, instead of manually splitting and converting a line:
34
+
35
+ ```python
36
+ parts = input().split()
37
+ count = int(parts[0])
38
+ ratio = float(parts[1])
39
+ name = parts[2]
40
+ ```
41
+
42
+ You can describe the input once and receive typed values directly:
43
+
44
+ ```python
45
+ count, ratio, name = format_input("int float str")
46
+ ```
47
+
48
+ See [USAGE.MD](./USAGE.MD) for all supported types and format specifications.
49
+
50
+ ## Requirements
51
+
52
+ - Python 3.10 or newer
53
+ - `regex` 2026.1.15 or newer
54
+
55
+ ## Installation
56
+
57
+ Install the published package from PyPI:
58
+
59
+ ```bash
60
+ pip install format-input
61
+ ```
62
+
63
+ Or clone the repository and install it manually:
64
+
65
+ Clone the repository:
66
+
67
+ ```bash
68
+ git clone https://github.com/GabbaTK/Format-Input.git
69
+ cd Format-Input
70
+ ```
71
+
72
+ The package is stored in `src/`.
73
+
74
+
75
+ To run the test suite from the repository root:
76
+
77
+ ```bash
78
+ PYTHONPATH=src python -m unittest discover -s tests -v
79
+ ```
80
+
81
+ ## License
82
+
83
+ This project is available under the [MIT License](./LICENSE).
84
+
85
+ ## AI disclosure
86
+
87
+ No AI was used in the making of the code.
@@ -1,4 +1,5 @@
1
1
  LICENSE
2
+ README.MD
2
3
  pyproject.toml
3
4
  src/format_input/__init__.py
4
5
  src/format_input/format_input.py
@@ -7,6 +8,7 @@ src/format_input/helpers.py
7
8
  src/format_input.egg-info/PKG-INFO
8
9
  src/format_input.egg-info/SOURCES.txt
9
10
  src/format_input.egg-info/dependency_links.txt
11
+ src/format_input.egg-info/requires.txt
10
12
  src/format_input.egg-info/top_level.txt
11
13
  tests/test_000_edgecase.py
12
14
  tests/test_a_basic_dtype.py
@@ -15,4 +17,6 @@ tests/test_c_basic_dtype_list_len.py
15
17
  tests/test_d_basic_dtype_greedy.py
16
18
  tests/test_e_named_dtype.py
17
19
  tests/test_f_extra.py
20
+ tests/test_g_groups.py
21
+ tests/test_h_times_group.py
18
22
  tests/test_mix_abcd.py
@@ -0,0 +1 @@
1
+ regex>=2026.1.15
@@ -74,6 +74,54 @@ class Test000Edgecase(unittest.TestCase):
74
74
  source = io.StringIO("42")
75
75
  self.assertEqual(format_input("count:int extra:?", source, named_variables=True), {"count": 42, "extra": ""})
76
76
 
77
+ def test17(self):
78
+ source = io.StringIO("")
79
+ with self.assertRaises(EOFError):
80
+ format_input("[int]", source)
81
+
82
+ def test18(self):
83
+ source = io.StringIO("42")
84
+ with self.assertRaises(IndexError):
85
+ format_input("[int int]", source)
86
+
87
+ def test19(self):
88
+ source = io.StringIO("not-an-int")
89
+ self.assertEqual(format_input("[int]", source), [[None]])
90
+
91
+ def test20(self):
92
+ source = io.StringIO("nan")
93
+ self.assertEqual(format_input("[float]", source), [[None]])
94
+
95
+ def test21(self):
96
+ source = io.StringIO("1 2")
97
+ self.assertEqual(format_input("[int[3]]", source), [[[1, 2]]])
98
+
99
+ def test22(self):
100
+ source = io.StringIO("1 word 2")
101
+ self.assertEqual(format_input("[int[]]", source), [[[1]]])
102
+
103
+ def test23(self):
104
+ source = io.StringIO("42 extra tokens")
105
+ self.assertEqual(format_input("[int]", source), [[42]])
106
+
107
+ def test24(self):
108
+ source = io.StringIO("\n")
109
+ self.assertEqual(format_input("[str]", source), [[""]])
110
+
111
+ def test25(self):
112
+ source = io.StringIO("42\r\nhello\r\n")
113
+ self.assertEqual(format_input("[int ; str]", source), [[42, "hello"]])
114
+
115
+ def test26(self):
116
+ source = io.StringIO("42")
117
+ with self.assertRaises(TypeError):
118
+ format_input("[int]", source, named_variables=True)
119
+
120
+ def test27(self):
121
+ source = io.StringIO("42")
122
+ with self.assertRaises(TypeError):
123
+ format_input("[count:int]", source, named_variables=True)
124
+
77
125
 
78
126
  if __name__ == "__main__":
79
127
  unittest.main()
@@ -0,0 +1,170 @@
1
+ import io
2
+ import unittest
3
+
4
+ from format_input import format_input
5
+
6
+
7
+ class TestGGroups(unittest.TestCase):
8
+ def test_simple1(self):
9
+ source = io.StringIO("Hello World")
10
+ self.assertEqual(format_input("[ str str ]", source), [["Hello", "World"]])
11
+
12
+ def test_simple2(self):
13
+ source = io.StringIO("42")
14
+ self.assertEqual(format_input("[int]", source), [[42]])
15
+
16
+ def test_simple3(self):
17
+ source = io.StringIO("3.14")
18
+ self.assertEqual(format_input("[float]", source), [[3.14]])
19
+
20
+ def test_simple4(self):
21
+ source = io.StringIO("hello")
22
+ self.assertEqual(format_input("[str]", source), [["hello"]])
23
+
24
+ def test_simple5(self):
25
+ source = io.StringIO("42 3.14 hello")
26
+ self.assertEqual(format_input("[int float str]", source), [[42, 3.14, "hello"]])
27
+
28
+ def test_simple6(self):
29
+ source = io.StringIO("10 20")
30
+ self.assertEqual(format_input("[int int]", source), [[10, 20]])
31
+
32
+ def test_simple7(self):
33
+ source = io.StringIO("1 2 3")
34
+ self.assertEqual(format_input("[int[2]]", source), [[[1, 2]]])
35
+
36
+ def test_simple8(self):
37
+ source = io.StringIO("1.5 2.5")
38
+ self.assertEqual(format_input("[float[2]]", source), [[[1.5, 2.5]]])
39
+
40
+ def test_simple9(self):
41
+ source = io.StringIO("red blue")
42
+ self.assertEqual(format_input("[str[2]]", source), [[["red", "blue"]]])
43
+
44
+ def test_simple10(self):
45
+ source = io.StringIO("1 2 3")
46
+ self.assertEqual(format_input("[int[]]", source), [[[1, 2, 3]]])
47
+
48
+ def test_simple11(self):
49
+ source = io.StringIO("1.25 2.5")
50
+ self.assertEqual(format_input("[float[]]", source), [[[1.25, 2.5]]])
51
+
52
+ def test_simple12(self):
53
+ source = io.StringIO("1 2 1.5 2.5")
54
+ self.assertEqual(format_input("[int[2] float[2]]", source), [[[1, 2], [1.5, 2.5]]])
55
+
56
+ def test_simple13(self):
57
+ source = io.StringIO("1 2 3.5 4.5")
58
+ self.assertEqual(format_input("[int[] float[]]", source), [[[1, 2], [3.5, 4.5]]])
59
+
60
+ def test_simple14(self):
61
+ source = io.StringIO("hello 42")
62
+ self.assertEqual(format_input("[hello:str* int]", source), [["hello", 42]])
63
+
64
+ def test_simple15(self):
65
+ source = io.StringIO("42 hello")
66
+ self.assertEqual(format_input("[[int str]]", source), [[[42, "hello"]]])
67
+
68
+ def test_newline1(self):
69
+ source = io.StringIO("42\nhello")
70
+ self.assertEqual(format_input("[int ; str]", source), [[42, "hello"]])
71
+
72
+ def test_newline2(self):
73
+ source = io.StringIO("1 2\n1.5 2.5")
74
+ self.assertEqual(format_input("[int[2] ; float[2]]", source), [[[1, 2], [1.5, 2.5]]])
75
+
76
+ def test_newline3(self):
77
+ source = io.StringIO("hello\n42\n3.5")
78
+ self.assertEqual(format_input("[str ; int ; float]", source), [["hello", 42, 3.5]])
79
+
80
+ def test_newline4(self):
81
+ source = io.StringIO("42 3.5\nhello world")
82
+ self.assertEqual(format_input("[int float ; str str]", source), [[42, 3.5, "hello", "world"]])
83
+
84
+ def test_newline5(self):
85
+ source = io.StringIO("42 hello\nworld")
86
+ self.assertEqual(format_input("[int [str ; str]]", source), [[42, ["hello", "world"]]])
87
+
88
+ def test_mix1(self):
89
+ source = io.StringIO("42 hello world")
90
+ self.assertEqual(format_input("int [str str]", source), [42, ["hello", "world"]])
91
+
92
+ def test_mix2(self):
93
+ source = io.StringIO("3.5 10 20")
94
+ self.assertEqual(format_input("float [int int]", source), [3.5, [10, 20]])
95
+
96
+ def test_mix3(self):
97
+ source = io.StringIO("alpha 1.25 42")
98
+ self.assertEqual(format_input("str [float int]", source), ["alpha", [1.25, 42]])
99
+
100
+ def test_mix4(self):
101
+ source = io.StringIO("42 3.5 hello world")
102
+ self.assertEqual(format_input("int float [str str]", source), [42, 3.5, ["hello", "world"]])
103
+
104
+ def test_mix5(self):
105
+ source = io.StringIO("1 2 3.5 hello")
106
+ self.assertEqual(format_input("int[2] [float str]", source), [[1, 2], [3.5, "hello"]])
107
+
108
+ def test_mix6(self):
109
+ source = io.StringIO("note words 42 3.5")
110
+ self.assertEqual(format_input("str* int [float]", source), ["note words", 42, [3.5]])
111
+
112
+ def test_mix7(self):
113
+ source = io.StringIO("42 hello extra words")
114
+ self.assertEqual(format_input("int [str*]", source), [42, ["hello extra words"]])
115
+
116
+ def test_mix8(self):
117
+ source = io.StringIO("0.5 1 2 3")
118
+ self.assertEqual(format_input("float [int[2]]", source), [0.5, [[1, 2]]])
119
+
120
+ def test_mix9(self):
121
+ source = io.StringIO("42 hello\n3.5")
122
+ self.assertEqual(format_input("int [str ; float]", source), [42, ["hello", 3.5]])
123
+
124
+ def test_mix10(self):
125
+ source = io.StringIO("1 2 hello\n3.5")
126
+ self.assertEqual(format_input("int [int [str ; float]]", source), [1, [2, ["hello", 3.5]]])
127
+
128
+ def test_named1(self):
129
+ source = io.StringIO("42")
130
+ self.assertEqual(format_input("record:[count:int]", source, named_variables=True), {"record": {"count": 42}})
131
+
132
+ def test_named2(self):
133
+ source = io.StringIO("Ada 36")
134
+ self.assertEqual(format_input("person:[name:str age:int]", source, named_variables=True), {"person": {"name": "Ada", "age": 36}})
135
+
136
+ def test_named3(self):
137
+ source = io.StringIO("3.5")
138
+ self.assertEqual(format_input("measurement:[ratio:float]", source, named_variables=True), {"measurement": {"ratio": 3.5}})
139
+
140
+ def test_named4(self):
141
+ source = io.StringIO("1 2 3")
142
+ self.assertEqual(format_input("record:[values:int[2]]", source, named_variables=True), {"record": {"values": [1, 2]}})
143
+
144
+ def test_named5(self):
145
+ source = io.StringIO("red blue")
146
+ self.assertEqual(format_input("record:[colors:str[2]]", source, named_variables=True), {"record": {"colors": ["red", "blue"]}})
147
+
148
+ def test_named6(self):
149
+ source = io.StringIO("1.25 2.5")
150
+ self.assertEqual(format_input("record:[values:float[]]", source, named_variables=True), {"record": {"values": [1.25, 2.5]}})
151
+
152
+ def test_named7(self):
153
+ source = io.StringIO("hello extra words")
154
+ self.assertEqual(format_input("record:[text:str*]", source, named_variables=True), {"record": {"text": "hello extra words"}})
155
+
156
+ def test_named8(self):
157
+ source = io.StringIO("extra words")
158
+ self.assertEqual(format_input("record:[extra:?]", source, named_variables=True), {"record": {"extra": "extra words"}})
159
+
160
+ def test_named9(self):
161
+ source = io.StringIO("Ada\n36")
162
+ self.assertEqual(format_input("person:[name:str ; age:int]", source, named_variables=True), {"person": {"name": "Ada", "age": 36}})
163
+
164
+ def test_named10(self):
165
+ source = io.StringIO("profile 42 3.5")
166
+ self.assertEqual(format_input("kind:str record:[count:int ratio:float]", source, named_variables=True), {"kind": "profile", "record": {"count": 42, "ratio": 3.5}})
167
+
168
+
169
+ if __name__ == "__main__":
170
+ unittest.main()
@@ -0,0 +1,110 @@
1
+ import io
2
+ import unittest
3
+
4
+ from format_input import format_input
5
+
6
+
7
+ class TestHTimesGroup(unittest.TestCase):
8
+ def test_simple1(self):
9
+ source = io.StringIO("Hello Python World")
10
+ self.assertEqual(format_input("3 * [ str ]", source), [["Hello"], ["Python"], ["World"]])
11
+
12
+ def test_simple2(self):
13
+ source = io.StringIO("10 20")
14
+ self.assertEqual(format_input("2 * [ int ]", source), [[10], [20]])
15
+
16
+ def test_simple3(self):
17
+ source = io.StringIO("1 apple 2 banana")
18
+ self.assertEqual(format_input("2 * [ int str ]", source), [[1, "apple"], [2, "banana"]])
19
+
20
+ def test_simple4(self):
21
+ source = io.StringIO("1 red blue 2 green yellow")
22
+ self.assertEqual(format_input("2 * [ int [ str str ] ]", source), [[1, ["red", "blue"]], [2, ["green", "yellow"]]])
23
+
24
+ def test_simple5(self):
25
+ source = io.StringIO("1 2 3 4")
26
+ self.assertEqual(format_input("2 * [ int[2] ]", source), [[[1, 2]], [[3, 4]]])
27
+
28
+ def test_simple6(self):
29
+ source = io.StringIO("2 10 20")
30
+ self.assertEqual(format_input("int * [ int ]", source), [2, [10], [20]])
31
+
32
+ def test_simple7(self):
33
+ source = io.StringIO("2 hello world")
34
+ self.assertEqual(format_input("N * [ str ]", source), [["hello"], ["world"]])
35
+
36
+ def test_simple8(self):
37
+ source = io.StringIO("3 one 1 two 2 three 3")
38
+ self.assertEqual(format_input("int * [ str int ]", source), [3, ["one", 1], ["two", 2], ["three", 3]])
39
+
40
+ def test_simple9(self):
41
+ source = io.StringIO("3 red blue green")
42
+ self.assertEqual(format_input("N * [ str ]", source), [["red"], ["blue"], ["green"]])
43
+
44
+ def test_simple10(self):
45
+ source = io.StringIO("2 10 20 30 40")
46
+ self.assertEqual(format_input("int * [ int[2] ]", source), [2, [[10, 20]], [[30, 40]]])
47
+
48
+ def test_simple11(self):
49
+ source = io.StringIO("2 3 4")
50
+ self.assertEqual(format_input("1*[n:int] n*[int]", source), [[2], [3], [4]])
51
+
52
+ def test_shrink1(self):
53
+ source = io.StringIO("2 10 20")
54
+ self.assertEqual(format_input("int * [ int ]", source, shrink_output_in_times_group=True), [2, 10, 20])
55
+
56
+ def test_shrink2(self):
57
+ source = io.StringIO("2 hello world")
58
+ self.assertEqual(format_input("N * [ str ]", source, shrink_output_in_times_group=True), ["hello", "world"])
59
+
60
+ def test_shrink3(self):
61
+ source = io.StringIO("2 10 red 20 blue")
62
+ self.assertEqual(format_input("int * [ int str ]", source, shrink_output_in_times_group=True), [2, [10, "red"], [20, "blue"]])
63
+
64
+ def test_newline1(self):
65
+ source = io.StringIO("1\napple\n2\nbanana")
66
+ self.assertEqual(format_input("2 * [ int ; str ]", source), [[1, "apple"], [2, "banana"]])
67
+
68
+ def test_newline2(self):
69
+ source = io.StringIO("2\n1\napple\n2\nbanana")
70
+ self.assertEqual(format_input("int * [ int ; str ]", source), [2, [1, "apple"], [2, "banana"]])
71
+
72
+ def test_newline3(self):
73
+ source = io.StringIO("2\napple\n1\nbanana\n2")
74
+ self.assertEqual(format_input("N * [ str ; int ]", source), [["apple", 1], ["banana", 2]])
75
+
76
+ def test_newline4(self):
77
+ source = io.StringIO("2\nalpha\n1\nbeta\n2")
78
+ self.assertEqual(format_input("int * [ str ; int ]", source), [2, ["alpha", 1], ["beta", 2]])
79
+
80
+ def test_newline5(self):
81
+ source = io.StringIO("3\nred\nblue\ngreen")
82
+ self.assertEqual(format_input("N * [ str ]", source), [["red"], ["blue"], ["green"]])
83
+
84
+ def test_newline6(self):
85
+ source = io.StringIO("3 one two three\nfour five six\nseven eight nine")
86
+ self.assertEqual(format_input("int * [ str str ; ]", source), [3, ["one", "two"], ["four", "five"], ["seven", "eight"]])
87
+
88
+ def test_var1(self):
89
+ source = io.StringIO("2\n10 20")
90
+ self.assertEqual(format_input("n:int ; n * [ int ]", source), [2, [10], [20]])
91
+
92
+ def test_var2(self):
93
+ source = io.StringIO("2\n1\napple\n2\nbanana")
94
+ self.assertEqual(format_input("n:int ; n * [ int ; str ]", source), [2, [1, "apple"], [2, "banana"]])
95
+
96
+ def test_nested1(self):
97
+ source = io.StringIO("2\n2\n10\n11\n1\n20")
98
+ self.assertEqual(format_input("int * [ int * [ int ] ]", source), [2, [2, [10], [11]], [1, [20]]])
99
+
100
+ def test_nested2(self):
101
+ source = io.StringIO("2\n2\n10\n11\n1\n20")
102
+ self.assertEqual(format_input("int * [ N * [ int ] ]", source), [2, [[10], [11]], [[20]]])
103
+
104
+ def test_nested3(self):
105
+ source = io.StringIO("2\n10\n11\n20\n21")
106
+ self.assertEqual(format_input("n:int ; 2 * [ n * [ int ] ]", source), [2, [[10], [11]], [[20], [21]]])
107
+
108
+
109
+ if __name__ == "__main__":
110
+ unittest.main()
@@ -1,14 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: format-input
3
- Version: 0.2.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
@@ -1,73 +0,0 @@
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_extra>\?)(?![\w?])" # e:?
12
- rf"|{NAME_PREFIX}(?P<named_type_greedy>str\*)(?![\w*])" # t:str*
13
- rf"|{NAME_PREFIX}(?P<named_type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # n:int[5] f:float[7] t:str[1]
14
- rf"|{NAME_PREFIX}(?P<named_type_list>(?:int|str|float)\[\])(?![\w\[])" # n:int[] f:float[] t:str[]
15
- rf"|{NAME_PREFIX}(?P<named_type>(?:int|str|float))\b" # n:int f:float t:str
16
- r"|(?<![\w:])(?P<extra>\?)(?![\w?])" # ?
17
- r"|\b(?P<type_greedy>str\*)(?![\w*])" # str*
18
- r"|\b(?P<type_len_list>(?:int|float|str)\[[1-9]\d*\])(?![\w\[])" # int[5] float[7] str[1]
19
- r"|\b(?P<type_list>(?:int|str|float)\[\])(?![\w\[])" # int[] float[] str[]
20
- r"|\b(?P<type>int|str|float)\b" # int float str
21
- )
22
-
23
-
24
- def readline(stream: typing.TextIO) -> str:
25
- line = stream.readline()
26
- #if line == "": raise EOFError()
27
- return line.rstrip("\r\n")
28
-
29
-
30
- def format_input(spec: str, stream: typing.TextIO | None = None, named_variables: bool = False) -> list[typing.Any] | dict[str, typing.Any]:
31
- if stream is None: stream = sys.stdin
32
-
33
- output = {} if named_variables else []
34
- inp_queue: deque[str] = deque()
35
- lines = RE_NEW_LINE.split(spec)
36
-
37
- for line in lines:
38
- inp = readline(stream)
39
- inps = inp.split(" ")
40
- inp_queue.clear()
41
- inp_queue.extend(inps)
42
-
43
- for m in RE_LINE_MATCH.finditer(line):
44
-
45
- #if len(inp_queue) == 0: raise EOFError("Tried to parse an empty input queue.")
46
-
47
- if "named" in m.lastgroup: var, dt = m.group().split(":")
48
- else: dt = m.group()
49
-
50
- match (m.lastgroup):
51
- case "named_extra": ret = handle_extra(inp_queue)
52
- case "extra": ret = handle_extra(inp_queue)
53
- case "named_type_greedy": ret = handle_type_greedy(inp_queue)
54
- case "type_greedy": ret = handle_type_greedy(inp_queue)
55
- case "named_type_len_list": ret = handle_type_list(dt, inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
56
- case "type_len_list": ret = handle_type_list(dt, inp_queue, max_size=int(m.group().split("[", 1)[1][:-1]))
57
- case "named_type_list": ret = handle_type_list(dt, inp_queue, max_size=-1)
58
- case "type_list": ret = handle_type_list(dt, inp_queue, max_size=-1)
59
- case "named_type": ret = handle_type(dt, inp_queue)
60
- case "type": ret = handle_type(dt, inp_queue)
61
-
62
- if "named" in m.lastgroup: ret = {var: ret}
63
-
64
- if isinstance(ret, dict) and not named_variables:
65
- output.extend([ v for v in ret.values() ])
66
- elif isinstance(ret, dict) and named_variables:
67
- output.update(ret)
68
- elif not isinstance(ret, dict) and not named_variables:
69
- output.append(ret)
70
- else:
71
- raise TypeError("Cannot add an unnamed value to named_variables=True")
72
-
73
- return output
@@ -1,14 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: format-input
3
- Version: 0.2.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
File without changes
File without changes