argparcel 0.0.1__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.
- argparcel/__init__.py +227 -0
- argparcel/py.typed +0 -0
- argparcel-0.0.1.dist-info/METADATA +105 -0
- argparcel-0.0.1.dist-info/RECORD +5 -0
- argparcel-0.0.1.dist-info/WHEEL +4 -0
argparcel/__init__.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import dataclasses
|
|
5
|
+
import enum
|
|
6
|
+
import types
|
|
7
|
+
import typing
|
|
8
|
+
|
|
9
|
+
if typing.TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
|
|
12
|
+
import _typeshed
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
__all__ = ["arg", "parse"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_HELP_KEY = "help"
|
|
19
|
+
"""A key to use in the 'metadata' for a dataclasses field for argparcel help."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _ensure_field_type(
|
|
23
|
+
name: str, type_: object
|
|
24
|
+
) -> (
|
|
25
|
+
type
|
|
26
|
+
| enum.EnumType
|
|
27
|
+
| types.UnionType
|
|
28
|
+
| typing._UnionGenericAlias # pyright: ignore [reportAttributeAccessIssue]
|
|
29
|
+
| typing._LiteralGenericAlias # pyright: ignore [reportAttributeAccessIssue]
|
|
30
|
+
):
|
|
31
|
+
if type(type_) not in (
|
|
32
|
+
type,
|
|
33
|
+
enum.EnumType,
|
|
34
|
+
types.UnionType,
|
|
35
|
+
typing._UnionGenericAlias, # pyright: ignore [reportAttributeAccessIssue] # noqa: SLF001
|
|
36
|
+
typing._LiteralGenericAlias, # pyright: ignore [reportAttributeAccessIssue] # noqa: SLF001
|
|
37
|
+
):
|
|
38
|
+
msg = f"Unsupported type for field '{name}': {type_} (of type {type(type_)})"
|
|
39
|
+
raise ValueError(msg)
|
|
40
|
+
return type_
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _Unspecified:
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_UNSPECIFIED = _Unspecified()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _add_argument(
|
|
51
|
+
parser: argparse.ArgumentParser,
|
|
52
|
+
*,
|
|
53
|
+
name: str,
|
|
54
|
+
help_: str | None,
|
|
55
|
+
required: bool,
|
|
56
|
+
default: object,
|
|
57
|
+
choices: Sequence | _Unspecified = _UNSPECIFIED,
|
|
58
|
+
type_: object = _UNSPECIFIED,
|
|
59
|
+
action: type[argparse.Action] | _Unspecified = _UNSPECIFIED,
|
|
60
|
+
) -> argparse.Action:
|
|
61
|
+
# Build up common arguments for `parser.add_argument` into this dictionary. This is
|
|
62
|
+
# the easiest way for us to avoid passing in arguments that should be unspecified.
|
|
63
|
+
kwargs: dict[str, typing.Any] = {}
|
|
64
|
+
if default is not _UNSPECIFIED:
|
|
65
|
+
kwargs["default"] = default
|
|
66
|
+
if choices is not _UNSPECIFIED:
|
|
67
|
+
kwargs["choices"] = choices
|
|
68
|
+
if type_ is not _UNSPECIFIED:
|
|
69
|
+
kwargs["type"] = type_
|
|
70
|
+
if action is not _UNSPECIFIED:
|
|
71
|
+
kwargs["action"] = action
|
|
72
|
+
|
|
73
|
+
return parser.add_argument(name, help=help_, required=required, **kwargs)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _add_argument_choices[T](
|
|
77
|
+
parser: argparse.ArgumentParser,
|
|
78
|
+
*,
|
|
79
|
+
name: str,
|
|
80
|
+
help_: str | None,
|
|
81
|
+
required: bool,
|
|
82
|
+
default: T,
|
|
83
|
+
choices: Sequence[T],
|
|
84
|
+
field_type: enum.EnumType | typing._LiteralGenericAlias, # pyright: ignore [reportAttributeAccessIssue]
|
|
85
|
+
field_name: str,
|
|
86
|
+
type_: object = _UNSPECIFIED,
|
|
87
|
+
) -> argparse.Action:
|
|
88
|
+
if len(choices) == 0:
|
|
89
|
+
msg = f"Need at least one choice for field '{field_name}' of type {field_type}"
|
|
90
|
+
raise ValueError(msg)
|
|
91
|
+
|
|
92
|
+
if type_ is _UNSPECIFIED:
|
|
93
|
+
choice_types = {type(x) for x in choices}
|
|
94
|
+
# We enforce that all choices MUST all be of the same type, so that we can
|
|
95
|
+
# convert them simply and unambiguously (e.g. `Literal[42, "42"]` could cause
|
|
96
|
+
# problems).
|
|
97
|
+
if len(choice_types) != 1:
|
|
98
|
+
msg = (
|
|
99
|
+
"Need exactly one type of choice. "
|
|
100
|
+
f"Found {choice_types} for {field_type}, for field '{field_name}'"
|
|
101
|
+
)
|
|
102
|
+
raise ValueError(msg)
|
|
103
|
+
|
|
104
|
+
(type_,) = choice_types
|
|
105
|
+
|
|
106
|
+
return _add_argument(
|
|
107
|
+
parser,
|
|
108
|
+
name=name,
|
|
109
|
+
type_=type_,
|
|
110
|
+
choices=choices,
|
|
111
|
+
help_=help_,
|
|
112
|
+
required=required,
|
|
113
|
+
default=default,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _add_argument_from_field(
|
|
118
|
+
parser: argparse.ArgumentParser,
|
|
119
|
+
field: dataclasses.Field,
|
|
120
|
+
name_to_type: Mapping[str, object],
|
|
121
|
+
) -> None:
|
|
122
|
+
name = f"--{field.name.replace('_', '-')}"
|
|
123
|
+
no_default = field.default is dataclasses.MISSING
|
|
124
|
+
field_type = _ensure_field_type(field.name, name_to_type[field.name])
|
|
125
|
+
help_ = field.metadata.get(_HELP_KEY)
|
|
126
|
+
if not (help_ is None or isinstance(help_, str)):
|
|
127
|
+
msg = f"Unsupported help metadata for field '{field.name}': {help_!r}"
|
|
128
|
+
raise ValueError(msg)
|
|
129
|
+
|
|
130
|
+
if isinstance(
|
|
131
|
+
field_type,
|
|
132
|
+
types.UnionType | typing._UnionGenericAlias, # pyright: ignore [reportAttributeAccessIssue] # noqa: SLF001
|
|
133
|
+
):
|
|
134
|
+
base_types = typing.get_args(field_type)
|
|
135
|
+
allow_missing = any(x is types.NoneType for x in base_types)
|
|
136
|
+
non_none_types = tuple(x for x in base_types if x is not types.NoneType)
|
|
137
|
+
if len(non_none_types) != 1:
|
|
138
|
+
msg = f"Can only support one non-None type for '{field.name}': {field.type}"
|
|
139
|
+
raise ValueError(msg)
|
|
140
|
+
base_type = non_none_types[0]
|
|
141
|
+
else:
|
|
142
|
+
allow_missing = False
|
|
143
|
+
base_type = field_type
|
|
144
|
+
|
|
145
|
+
default = _UNSPECIFIED if no_default else field.default
|
|
146
|
+
|
|
147
|
+
# An argument is 'required' if the user MUST specify it on the command line.
|
|
148
|
+
required = no_default and (not allow_missing)
|
|
149
|
+
|
|
150
|
+
if base_type is bool:
|
|
151
|
+
# Represent boolean arguments as 'flags'
|
|
152
|
+
_add_argument(
|
|
153
|
+
parser=parser,
|
|
154
|
+
name=name,
|
|
155
|
+
action=argparse.BooleanOptionalAction,
|
|
156
|
+
help_=help_,
|
|
157
|
+
required=required,
|
|
158
|
+
default=default,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
elif isinstance(base_type, typing._LiteralGenericAlias): # pyright: ignore [reportAttributeAccessIssue] # noqa: SLF001
|
|
162
|
+
# Represent literal arguments with choices.
|
|
163
|
+
_add_argument_choices(
|
|
164
|
+
parser,
|
|
165
|
+
name=name,
|
|
166
|
+
choices=typing.get_args(base_type),
|
|
167
|
+
help_=help_,
|
|
168
|
+
required=required,
|
|
169
|
+
default=default,
|
|
170
|
+
field_type=field.type,
|
|
171
|
+
field_name=field.name,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
elif isinstance(base_type, enum.EnumType):
|
|
175
|
+
# FIXME: This is inconsistent.
|
|
176
|
+
# The help description lists the choices as e.g. `EnumName.a, EnumName.b`, but
|
|
177
|
+
# the users should just pass `a` and `b`. But if we change `choices` to be a
|
|
178
|
+
# sequence of strings, then the help becomes correct, but the parsing is then
|
|
179
|
+
# broken.
|
|
180
|
+
_add_argument_choices(
|
|
181
|
+
parser,
|
|
182
|
+
name=name,
|
|
183
|
+
type_=base_type.__getitem__, # Look up the enum element by name.
|
|
184
|
+
choices=tuple(base_type), # Sequence of elements.
|
|
185
|
+
help_=help_,
|
|
186
|
+
required=required,
|
|
187
|
+
default=default,
|
|
188
|
+
field_type=field.type,
|
|
189
|
+
field_name=field.name,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
else:
|
|
193
|
+
_add_argument(
|
|
194
|
+
parser,
|
|
195
|
+
name=name,
|
|
196
|
+
type_=base_type,
|
|
197
|
+
help_=help_,
|
|
198
|
+
required=required,
|
|
199
|
+
default=default,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def arg(
|
|
204
|
+
*,
|
|
205
|
+
default: object = dataclasses.MISSING,
|
|
206
|
+
help: str | None = None, # noqa: A002
|
|
207
|
+
) -> typing.Any: # noqa: ANN401
|
|
208
|
+
"""Create a dataclasses.Field in a way that argparcel understands."""
|
|
209
|
+
return dataclasses.field(default=default, metadata={_HELP_KEY: help})
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def parse[T: _typeshed.DataclassInstance](
|
|
213
|
+
cls: type[T],
|
|
214
|
+
command_line: Sequence[str] | None = None,
|
|
215
|
+
*,
|
|
216
|
+
exit_on_error: bool = False,
|
|
217
|
+
) -> T:
|
|
218
|
+
"""Parse arguments into an instance of `cls`."""
|
|
219
|
+
parser = argparse.ArgumentParser(exit_on_error=exit_on_error)
|
|
220
|
+
|
|
221
|
+
# If 'future annotations' are in use, `Field.type` may be a string. If we use
|
|
222
|
+
# `get_type_hints`, then these will get resolved into the actual runtime types.
|
|
223
|
+
name_to_type = typing.get_type_hints(cls)
|
|
224
|
+
for field in dataclasses.fields(cls):
|
|
225
|
+
_add_argument_from_field(parser, field, name_to_type)
|
|
226
|
+
|
|
227
|
+
return cls(**parser.parse_args(command_line).__dict__)
|
argparcel/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: argparcel
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Parse command-line arguments into a dataclass
|
|
5
|
+
Author: Tom Gillam
|
|
6
|
+
Author-email: Tom Gillam <tpgillam@googlemail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Natural Language :: English
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Requires-Python: >=3.12
|
|
15
|
+
Project-URL: Homepage, https://github.com/tpgillam/argparcel
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# argparcel
|
|
19
|
+
|
|
20
|
+
A minimalist library to parse command-line arguments into a dataclass.
|
|
21
|
+
|
|
22
|
+
## Example usage
|
|
23
|
+
```python
|
|
24
|
+
import dataclasses
|
|
25
|
+
import pathlib
|
|
26
|
+
from typing import Literal
|
|
27
|
+
|
|
28
|
+
import argparcel
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
|
|
32
|
+
class Moo:
|
|
33
|
+
a: int | None
|
|
34
|
+
b: float
|
|
35
|
+
choice: Literal[1, 2, 3] | None = argparcel.arg(help="choose wisely")
|
|
36
|
+
path: pathlib.Path | None
|
|
37
|
+
c: bool = True
|
|
38
|
+
description: str | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
print(argparcel.parse(Moo, ["--a", "2", "--b", "3.2"]))
|
|
43
|
+
print(argparcel.parse(Moo, ["--a", "2", "--b", "3.2", "--no-c"]))
|
|
44
|
+
print(argparcel.parse(Moo, ["--b", "4", "--c"]))
|
|
45
|
+
print(argparcel.parse(Moo, ["--b", "4", "--c", "--description", "moo moo"]))
|
|
46
|
+
print(
|
|
47
|
+
argparcel.parse(
|
|
48
|
+
Moo,
|
|
49
|
+
[
|
|
50
|
+
"--b",
|
|
51
|
+
"4",
|
|
52
|
+
"--c",
|
|
53
|
+
"--description",
|
|
54
|
+
"moo moo",
|
|
55
|
+
"--path",
|
|
56
|
+
"/somewhere/over/the/rainbow",
|
|
57
|
+
],
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```console
|
|
63
|
+
Moo(a=2, b=3.2, choice=1, path=None, c=True, description=None)
|
|
64
|
+
Moo(a=2, b=3.2, choice=3, path=None, c=False, description=None)
|
|
65
|
+
Moo(a=None, b=4.0, choice=None, path=None, c=True, description=None)
|
|
66
|
+
Moo(a=None, b=4.0, choice=None, path=None, c=True, description='moo moo')
|
|
67
|
+
Moo(
|
|
68
|
+
a=None,
|
|
69
|
+
b=4.0,
|
|
70
|
+
choice=None,
|
|
71
|
+
path=PosixPath('/somewhere/over/the/rainbow'),
|
|
72
|
+
c=True,
|
|
73
|
+
description='moo moo'
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Another example:
|
|
79
|
+
```python
|
|
80
|
+
class Thingy(enum.Enum):
|
|
81
|
+
a = enum.auto()
|
|
82
|
+
b = enum.auto()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
|
|
86
|
+
class Moo2:
|
|
87
|
+
choice: Literal[1, 2, 3] | None
|
|
88
|
+
no_choice: Literal["foo", "bar"] = argparcel.arc(help="baz")
|
|
89
|
+
thingy: Thingy = Thingy.a
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
argparcel.parse(Moo2, ["--help"])
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```console
|
|
96
|
+
usage: moo.py [-h] [--choice {1,2,3}] --no-choice {foo,bar}
|
|
97
|
+
[--thingy {Thingy.a,Thingy.b}]
|
|
98
|
+
|
|
99
|
+
options:
|
|
100
|
+
-h, --help show this help message and exit
|
|
101
|
+
--choice {1,2,3}
|
|
102
|
+
--no-choice {foo,bar}
|
|
103
|
+
baz
|
|
104
|
+
--thingy {Thingy.a,Thingy.b}
|
|
105
|
+
```
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
argparcel/py.typed,sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855,0
|
|
2
|
+
argparcel/__init__.py,sha256=ad63a362eeea8f7e24f19ecec594d84c4455fab0b49d97ae84172c6a55277cf7,7241
|
|
3
|
+
argparcel-0.0.1.dist-info/WHEEL,sha256=1c77bbda0b527f376a68ced20cbc1aac3efc7bc4d7c10cc4323a905ef79ae8db,78
|
|
4
|
+
argparcel-0.0.1.dist-info/METADATA,sha256=a816f2174209664e132008bfb796c15b4a76aaf95bf9041a983d5c812c36cdef,2614
|
|
5
|
+
argparcel-0.0.1.dist-info/RECORD,,
|