argx 0.4.2__tar.gz → 0.4.4__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.
@@ -1,25 +1,18 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: argx
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: Super-charged argparse for python
5
+ Author-email: pwwang <pwwang@pwwang.com>
5
6
  License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
6
9
  License-File: LICENSE
7
- Author: pwwang
8
- Author-email: pwwang@pwwang.com
9
- Requires-Python: >=3.9,<4.0
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
- Classifier: Programming Language :: Python :: 3.14
10
+ Requires-Dist: python-simpleconf<1.0,>=0.9
18
11
  Provides-Extra: anypath
12
+ Requires-Dist: panpath<0.5,>=0.4; extra == "anypath"
19
13
  Provides-Extra: panpath
20
- Requires-Dist: panpath (>=0.4,<0.5) ; extra == "anypath" or extra == "panpath"
21
- Requires-Dist: python-simpleconf (>=0.8,<0.9)
22
- Description-Content-Type: text/markdown
14
+ Requires-Dist: panpath<0.5,>=0.4; extra == "panpath"
15
+ Dynamic: license-file
23
16
 
24
17
  # argx
25
18
 
@@ -457,4 +450,3 @@ All features are optional. You can use `argx` as a drop-in replacement for `argp
457
450
  [6]: https://img.shields.io/codacy/coverage/c5eaafcde482437b901b1acd2b70420e.svg?style=flat-square
458
451
  [7]: https://img.shields.io/github/actions/workflow/status/pwwang/argx/build.yml?style=flat-square
459
452
  [8]: https://img.shields.io/pypi/pyversions/argx.svg?style=flat-square
460
-
@@ -12,4 +12,15 @@ from argparse import (
12
12
 
13
13
  from .parser import ArgumentParser
14
14
 
15
- __version__ = "0.4.2"
15
+ __version__ = "0.4.4"
16
+
17
+ __all__ = [
18
+ "ArgumentParser",
19
+ "Namespace",
20
+ "ONE_OR_MORE",
21
+ "OPTIONAL",
22
+ "PARSER",
23
+ "REMAINDER",
24
+ "SUPPRESS",
25
+ "ZERO_OR_MORE",
26
+ ]
@@ -163,7 +163,7 @@ class ClearExtendAction(ClearAppendAction):
163
163
  items = getattr(ns, dest, None)
164
164
  items = copy_items(items)
165
165
 
166
- items.extend(values)
166
+ items.extend(values) # type: ignore[union-attr]
167
167
  setattr(ns, dest, items)
168
168
 
169
169
 
@@ -179,11 +179,13 @@ class NamespaceAction(_StoreAction):
179
179
  option_string: str | None = None,
180
180
  ) -> None:
181
181
  ns, dest = get_ns_dest(namespace, self.dest)
182
+ parsed = None
182
183
  if isinstance(values, str):
183
184
  try:
184
185
  parsed = json.loads(values)
185
- except json.JSONDecodeError:
186
+ except json.JSONDecodeError: # pragma: no cover
186
187
  parser.error(f"Invalid json for {option_string}: {values}")
188
+ return
187
189
 
188
190
  if not isinstance(parsed, dict):
189
191
  parser.error(f"Invalid json dictionary for {option_string}: {values}")
@@ -204,7 +206,7 @@ class SubParserAction(_SubParsersAction):
204
206
 
205
207
  def add_parser(self, *args, **kwargs) -> ArgumentParser:
206
208
  parser = super().add_parser(*args, **kwargs)
207
- parser.parent = self.parent
209
+ parser.parent = self.parent # type: ignore[assignment]
208
210
  return parser
209
211
 
210
212
 
@@ -219,8 +221,10 @@ class HelpAction(_HelpAction):
219
221
  ) -> None:
220
222
  parser.print_help(
221
223
  # This is a + option
222
- plus=option_string.endswith("+")
224
+ plus=option_string.endswith("+") # type: ignore[union-attr]
223
225
  # Or no + option defined at all, all options are shown
224
- or not any(h.endswith("+") for h in parser.add_help)
226
+ or not any(
227
+ h.endswith("+") for h in parser.add_help # type: ignore[union-attr]
228
+ )
225
229
  )
226
230
  parser.exit()
@@ -14,6 +14,8 @@ def import_pyfile(pyfile: PathLike | str) -> dict:
14
14
  import importlib.util
15
15
 
16
16
  spec = importlib.util.spec_from_file_location("config", pyfile)
17
+ if spec is None or spec.loader is None: # pragma: no cover
18
+ raise ImportError(f"Cannot import python file: {pyfile}")
17
19
  module = importlib.util.module_from_spec(spec)
18
20
  spec.loader.exec_module(module)
19
21
  try:
@@ -0,0 +1,452 @@
1
+ Metadata-Version: 2.4
2
+ Name: argx
3
+ Version: 0.4.4
4
+ Summary: Super-charged argparse for python
5
+ Author-email: pwwang <pwwang@pwwang.com>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: python-simpleconf<1.0,>=0.9
11
+ Provides-Extra: anypath
12
+ Requires-Dist: panpath<0.5,>=0.4; extra == "anypath"
13
+ Provides-Extra: panpath
14
+ Requires-Dist: panpath<0.5,>=0.4; extra == "panpath"
15
+ Dynamic: license-file
16
+
17
+ # argx
18
+
19
+ [![pypi][1]][2] [![tag][3]][2] [![codacy quality][4]][5] [![codacy quality][6]][5] ![github action][7] ![pyver][8]
20
+
21
+ Supercharged argparse for Python
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install -U argx
27
+ pip install -U argx[panpath] # to use panpath type
28
+ # see https://github.com/pwwang/panpath
29
+ ```
30
+
31
+ ## Features enhanced or added
32
+
33
+ - [Option `exit_on_void`](#option-exit_on_void): Exit with error if no arguments are provided
34
+ - [Subcommand shortcut](#subcommand-shortcut): Adding subcommands directly, without `parser.add_subparsers()`
35
+ - [Namespace arguments](#namespace-arguments): Access arguments like `--foo.bar` as `args.foo.bar`
36
+ - [Brief help message for massive arguments](#brief-help-message-for-massive-arguments): Show only the most important arguments in the help message
37
+ - [Default value in argument help](#default-value-in-argument-help): Show the default value in the help message of arguments
38
+ - [Newlines kept in help](#newlines-kept-in-help): Newlines are kept in argument help if any
39
+ - [Defaults from file](#defaults-from-files): Read default values from a configuration file by API or from command line
40
+ - [Clear-append/extend action](#clear_appendextend-action): Store a list of values. Different from `append` and `extend`, the initial value is cleared.
41
+ - [Grouping required arguments by default](#grouping-required-arguments-by-default): Put required arguments in 'required arguments' group, instead of 'optional arguments' group
42
+ - [Order of groups in help message](#order-of-groups-in-help-message): Allow to add an `order` attribute to groups to change the order of groups in help message
43
+ - [Additional types](#additional-types): Some additional types to convert the values of arguments
44
+ - [Configuration file to create the parser](#configuration-file-to-create-the-parser): Instead of creating the parser by code, you can also create it by a configuration file
45
+ - [API to get actions](#api-to-get-actions): Get the actions of the parser by API
46
+ - [Pre-parse hook](#pre-parse-hook): A hook to modify the arguments before parsing
47
+ - [Backward compatibility](#backward-compatibility): All features are optional. You can use `argx` as a drop-in replacement for `argparse`.
48
+
49
+ ### Option `exit_on_void`
50
+
51
+ If all arguments are optional, `argparse` will not raise an error if no arguments are provided. This is not always desirable. `argx` provides the option `exit_on_void` to change this behavior. If `exit_on_void` is set to `True` and no arguments are provided, `argx` will exit with an error (No arguments provided).
52
+
53
+ ```python
54
+ import argx as argparse
55
+
56
+ parser = argparse.ArgumentParser(exit_on_void=True)
57
+ parser.add_argument('--foo', action='store_true')
58
+
59
+ args = parser.parse_args([])
60
+ # No arguments provided
61
+ # standard argparse produces: Namespace(foo=False)
62
+ ```
63
+
64
+ ### Subcommand shortcut
65
+
66
+ `argparse` requires to create subparsers first and then add the subcommands to the subparsers.
67
+ `argx` allows to add subcommands directly to the main parser.
68
+
69
+ ```python
70
+ # standard argparse
71
+ parser = argparse.ArgumentParser()
72
+ subparsers = parser.add_subparsers(title='subcommands')
73
+ parser_a = subparsers.add_parser('a')
74
+ parser_b = subparsers.add_parser('b')
75
+
76
+ # argx
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_command('a') # or parser.add_subparser('a')
79
+ parser.add_command('b')
80
+ # args = parser.parse_args(['a'])
81
+ # Namespace(COMMAND='a')
82
+ ```
83
+
84
+ The `subparsers` is added automatically with the title `subcommands` and the `dest` is set to `COMMAND`. You can add subcommands to subcommands directly, then the `dest` is set to `COMMAND2`, `COMMAND3`, etc. If you want to change the behavior, you can always fall back to the standard `argparse` way.
85
+
86
+ ### Namespace arguments
87
+
88
+ The values of arguments like `--foo.bar` can be accessed as `vars(args)['foo.bar']`. With `argx` you can access them as `args.foo.bar`.
89
+
90
+ The arguments `--foo.bar`, `--foo.baz` and `--foo.qux` are automatically grouped in a namespace `foo`.
91
+
92
+ ```python
93
+ import argx as argparse
94
+
95
+ parser = argparse.ArgumentParser()
96
+ parser.add_argument('--foo.bar', type=int)
97
+ parser.add_argument('--foo.baz', type=int)
98
+ parser.add_argument('--foo.qux', type=int)
99
+
100
+ parser.print_help()
101
+ ```
102
+
103
+ ```shell
104
+ Usage: test.py [-h] [--foo.bar BAR] [--foo.baz BAZ] [--foo.qux QUX]
105
+
106
+ Optional arguments:
107
+ -h, --help show this help message and exit
108
+
109
+ Namespace <foo>:
110
+ --foo.bar BAR
111
+ --foo.baz BAZ
112
+ --foo.qux QUX
113
+ ```
114
+
115
+ You can modify the namespace by adding the namespace manually before adding the arguments.
116
+
117
+ ```python
118
+ import argx as argparse
119
+
120
+ parser = argparse.ArgumentParser()
121
+ parser.add_namespace('foo', title="Foo's options")
122
+ parser.add_argument('--foo.bar', type=int)
123
+ parser.add_argument('--foo.baz', type=int)
124
+ parser.add_argument('--foo.qux', type=int)
125
+
126
+ parser.print_help()
127
+ ```
128
+
129
+ ```shell
130
+ Usage: test.py [-h] [--foo.bar BAR] [--foo.baz BAZ] [--foo.qux QUX]
131
+
132
+ Optional Arguments:
133
+ -h, --help show this help message and exit
134
+
135
+ Foo's Options:
136
+ --foo.bar BAR
137
+ --foo.baz BAZ
138
+ --foo.qux QUX
139
+ ```
140
+
141
+ You can also add a namespace action argument to take a json that can be parsed as a dict:
142
+
143
+ ```python
144
+ import argx as argparse
145
+
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument('--foo', action="namespace") # or action="ns"
148
+ parser.add_argument('--foo.bar', type=int)
149
+ parser.add_argument('--foo.baz', type=int)
150
+ parser.add_argument('--foo.qux', type=int)
151
+
152
+ parser.parse_args(['--foo', '{"bar": 1, "baz": 2, "qux": 3}', '--foo.qux', '4'])
153
+ # Namespace(foo=Namespace(bar=1, baz=2, qux=4))
154
+ ```
155
+
156
+ ### Brief help message for massive arguments
157
+
158
+ If you have a lot of arguments, the help message can be very long. `argx` allows to show only the most important arguments in the help message.
159
+
160
+ ```python
161
+ import argx as argparse
162
+
163
+ # Advanced help options to show the brief help message or the full help message
164
+ parser = argparse.ArgumentParser(add_help='h,help,h+,help+')
165
+ parser.add_argument('--foo', type=int)
166
+ parser.add_argument('--bar', type=int, show=False)
167
+ parser.parse_args(['--help'])
168
+ ```
169
+
170
+ ```shell
171
+ Usage: test.py [-h] [--foo FOO]
172
+
173
+ Optional Arguments:
174
+ -h, --help, -h+, --help+
175
+ show help message (with + to show more options) and exit
176
+ --foo FOO
177
+ ```
178
+
179
+ With `parser.parse_args(['--help+'])` you can show the full help message.
180
+
181
+ ```shell
182
+ Usage: test.py [-h] [--foo FOO] [--bar BAR]
183
+
184
+ Optional Arguments:
185
+ -h, --help, -h+, --help+
186
+ show help message (with + to show more options) and exit
187
+ --foo FOO
188
+ --bar BAR
189
+ ```
190
+
191
+ You can also set `show=False` for argument groups.
192
+
193
+ ### Default value in argument help
194
+
195
+ With `argparse`, the default value is not shown in the help message. With `argx`, the default value is added to the help message automatically.
196
+
197
+ ```python
198
+ import argx as argparse
199
+
200
+ parser = argparse.ArgumentParser()
201
+ parser.add_argument('--foo', type=int, default=1)
202
+ parser.add_argument('--bar', type=int, default=2, help='bar [default: two]')
203
+ parser.add_argument('--baz', type=int, default=3, help='baz [nodefault]')
204
+ parser.print_help()
205
+ ```
206
+
207
+ ```shell
208
+ Usage: test.py [-h] [--foo FOO]
209
+
210
+ Optional Arguments:
211
+ -h, --help show help message and exit
212
+ --foo FOO [default: 1]
213
+ --bar BAR bar [default: two]
214
+ --baz BAZ baz
215
+ ```
216
+
217
+ ### Newlines kept in help
218
+
219
+ By default, `argparse` replaces the newlines with spaces in the argument help message. However, sometimes you want to keep the newlines. With `argx`, if there is not newline, it is handled as the default behavior. If there is a newline, the newlines and spaces are kept.
220
+
221
+ ```python
222
+ import argx as argparse
223
+
224
+ parser = argparse.ArgumentParser()
225
+ parser.add_argument('--foo', help='foo\n- bar\n indent also kept')
226
+ parser.print_help()
227
+ ```
228
+
229
+ ```shell
230
+ Usage: test.py [-h] [--foo FOO]
231
+
232
+ Optional Arguments:
233
+ -h, --help show this help message and exit
234
+ --foo FOO foo
235
+ - bar
236
+ indent also kept
237
+ ```
238
+
239
+ ### Defaults from files
240
+
241
+ With standard `argparse`, when `fromfile_prefix_chars` is set, the arguments can be read from a file. The file can be specified with `@filename`. The arguments in the file are separated by newlines by default.
242
+
243
+ With `argx`, Other than a text file to provide command line arguments, you can also provide other types of configuration files. The extension of the file can be `.json`, `.yaml`, `.ini`, `.env` or `.toml`.
244
+
245
+ ```python
246
+ import argx as argparse
247
+
248
+ parser = argparse.ArgumentParser()
249
+ parser.add_argument('--foo', type=int)
250
+ parser.add_argument('--bar', type=int)
251
+ parser.add_argument('--baz', type=int)
252
+
253
+ # config.json
254
+ # { "foo": 1, "bar": 2, "baz": 3 }
255
+ args = parser.parse_args(['@config.json'])
256
+ # Namespace(foo=1, bar=2, baz=3)
257
+ ```
258
+
259
+ You can also use `set_defaults_from_configs` method:
260
+
261
+ ```python
262
+ parser.set_defaults_from_configs('config.json')
263
+ ```
264
+
265
+ ### Clear_append/extend action
266
+
267
+ The `clear_append`/`clear_extend` action is similar to `append` and `extend`, but the initial value is cleared.
268
+
269
+ This is useful when you want to accept a new list of values from the command line, instead of append/extend to the existing list or default.
270
+
271
+ ```python
272
+ import argx as argparse
273
+
274
+ parser = argparse.ArgumentParser()
275
+ parser.add_argument('--foo', action='clear_append', default=[1, 2, 3], type=int)
276
+ parser.add_argument('--bar', action='append', default=[1, 2, 3], type=int)
277
+
278
+ args = parser.parse_args('--foo 4 --foo 5 --bar 4 --bar 5'.split())
279
+ # Namespace(foo=[4, 5], bar=[1, 2, 3, 4, 5])
280
+ ```
281
+
282
+ ### Grouping required arguments by default
283
+
284
+ By default, `argparse` puts both `required=True` and `required=False` arguments in the same group (optional arguments), which is sometimes confusing. `argx` groups `required=True` arguments in a separate group (required arguments).
285
+
286
+ ```python
287
+ import argx as argparse
288
+
289
+ parser = argparse.ArgumentParser()
290
+ parser.add_argument('--foo')
291
+ parser.add_argument('--bar', required=True)
292
+
293
+ parser.print_help()
294
+ ```
295
+
296
+ ```shell
297
+ Usage: test.py [-h] [--foo FOO] --bar BAR
298
+
299
+ Required Arguments:
300
+ --bar BAR
301
+
302
+ Optional Arguments:
303
+ -h, --help show help message and exit
304
+ --foo FOO
305
+ ```
306
+
307
+ ### Order of groups in help message
308
+
309
+ Allow to add an `order` attribute to groups to change the order of groups in help message
310
+
311
+ ```python
312
+ import argx as argparse
313
+
314
+ parser = argparse.ArgumentParser()
315
+ group1 = parser.add_argument_group('group1', order=2)
316
+ group1.add_argument('--foo')
317
+ group2 = parser.add_argument_group('group2', order=1)
318
+ group2.add_argument('--bar')
319
+
320
+ parser.print_help()
321
+ ```
322
+
323
+ ```shell
324
+ Usage: test.py [-h] [--bar BAR] [--foo FOO]
325
+
326
+ Optional arguments:
327
+ -h, --help show help message and exit
328
+
329
+ Group2:
330
+ --bar BAR
331
+
332
+ Group1:
333
+ --foo FOO
334
+ ```
335
+
336
+ The order by default is 0. The groups with the same order are sorted by title. Groups with small numbers are displayed first. `required arguments` has a `order` of -1.
337
+
338
+ ### Additional types
339
+
340
+ `parser.add_argument()` accepts `type` as a function to convert the argument value. It has to be a callable that accepts a single string argument and returns the converted value. While `argx` supports string for `type` so it can be configured in the configuration file. Builtin functions and types can also be specified by its name.
341
+
342
+ We also have additional types:
343
+
344
+ ```python
345
+ import argx as argparse
346
+
347
+ parser = argparse.ArgumentParser()
348
+ parser.add_argument('--foo', type='py')
349
+ parser.add_argument('--bar', type='json')
350
+ parser.add_argument('--baz', type='path')
351
+ parser.add_argument('--qux', type='auto')
352
+ parser.add_argument('--quux', type='panpath') # requires panpath
353
+
354
+ args = parser.parse_args(
355
+ '--foo 1 --bar {"a":1} --baz path/to/file --qux true --quux s3://path/to'.split()
356
+ )
357
+ # Namespace(
358
+ # foo=1, bar={'a': 1}, baz=PosixPath('path/to/file'),
359
+ # qux=True, quux=S3Path('s3://path/to')
360
+ # )
361
+ ```
362
+
363
+ - `py`: Python expression. The string is evaluated by `ast.literal_eval`.
364
+ - `json`: JSON string. The string is loaded by `json.loads`.
365
+ - `path`: Path string. The string is converted by `pathlib.Path`.
366
+ - `auto`: Automatic type conversion.
367
+ - `True` if the string is `True/TRUE/true`
368
+ - `False` if the string is `False/FALSE/false`
369
+ - `None` if the string is `None/NONE/none`
370
+ - An integer if the string can be converted to an integer
371
+ - A float if the string can be converted to a float
372
+ - A dict if the string is a JSON string
373
+ - The string itself otherwise
374
+
375
+ ### Configuration file to create the parser
376
+
377
+ You can create the parser from a configuration file.
378
+
379
+ ```python
380
+ import argx as argparse
381
+
382
+ # config.json
383
+ # {
384
+ # "prog": "myprog",
385
+ # "arguments": [ {"flags": ["-a", "--abc"], "help": "Optiona a help"} ]
386
+ # }
387
+ parser = argparse.ArgumentParser.from_configs('config.json')
388
+ parser.print_help()
389
+ ```
390
+
391
+ ```shell
392
+ Usage: myprog [-h] [-a ABC]
393
+
394
+ Optional Arguments:
395
+ -h, --help show help message and exit
396
+ -a ABC, --abc ABC Optiona a help
397
+ ```
398
+
399
+ ### API to get actions
400
+
401
+ You can get the actions of the parser by `.get_action()`.
402
+
403
+ ```python
404
+ import argx
405
+
406
+ parser = argx.ArgumentParser()
407
+ parser.add_argument('--foo', type=int)
408
+
409
+ action = parser.get_action('foo')
410
+ # StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None,
411
+ # default=None, type=<class 'int'>, choices=None, required=False, help=None,
412
+ # metavar=None)
413
+ ```
414
+
415
+ ### Pre-parse hook
416
+
417
+ You can add a pre-parse hook to the parser. The hook is called before parsing the arguments. It can be used to modify the arguments before parsing.
418
+
419
+ ```python
420
+ import argx as argparse
421
+
422
+ def pre_parse(parser, args, namespace):
423
+ """We can modify the parser (i.e. add arguments)
424
+ the arguments to be parsed, and even manipulate the namespace.
425
+ """
426
+ parser.add_argument('--foo', type=int)
427
+ parser.add_argument('--bar', type=int)
428
+ namespace.baz = 2
429
+ return args + ["--bar", "3"]
430
+
431
+ parser = argparse.ArgumentParser()
432
+ parser.add_command('command1', pre_parse=pre_parse)
433
+ parsed = parser.parse_args('command1 --foo 1'.split())
434
+ # Namespace(COMMAND='command1', baz=2, foo=1, bar=3)
435
+ ```
436
+
437
+ This is especially useful when you have a lot of subcommands and each has a lot of arguments, when it takes time to add these arguments, for example, some of the values need to be parsed from a file. Using this hook, you can add the arguments only when the subcommand is called, instead of adding them all at the beginning.
438
+
439
+ ### Backward compatibility
440
+
441
+ All features are optional. You can use `argx` as a drop-in replacement for `argparse`.
442
+
443
+ `argx` supports python `3.7+`. Some of the later-introduced features are also supported in python 3.7. For example, `extend` action is added in python 3.8, `argx` supports in python 3.7.
444
+
445
+ [1]: https://img.shields.io/pypi/v/argx.svg?style=flat-square
446
+ [2]: https://pypi.org/project/argx/
447
+ [3]: https://img.shields.io/github/tag/pwwang/argx.svg?style=flat-square
448
+ [4]: https://img.shields.io/codacy/grade/c5eaafcde482437b901b1acd2b70420e.svg?style=flat-square
449
+ [5]: https://app.codacy.com/gh/pwwang/argx/dashboard
450
+ [6]: https://img.shields.io/codacy/coverage/c5eaafcde482437b901b1acd2b70420e.svg?style=flat-square
451
+ [7]: https://img.shields.io/github/actions/workflow/status/pwwang/argx/build.yml?style=flat-square
452
+ [8]: https://img.shields.io/pypi/pyversions/argx.svg?style=flat-square
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ argx/__init__.py
6
+ argx/action.py
7
+ argx/formatter.py
8
+ argx/parser.py
9
+ argx/py.typed
10
+ argx/type_.py
11
+ argx/utils.py
12
+ argx.egg-info/PKG-INFO
13
+ argx.egg-info/SOURCES.txt
14
+ argx.egg-info/dependency_links.txt
15
+ argx.egg-info/requires.txt
16
+ argx.egg-info/top_level.txt
17
+ tests/test_action.py
18
+ tests/test_parser.py
19
+ tests/test_type.py
@@ -0,0 +1,7 @@
1
+ python-simpleconf<1.0,>=0.9
2
+
3
+ [anypath]
4
+ panpath<0.5,>=0.4
5
+
6
+ [panpath]
7
+ panpath<0.5,>=0.4
@@ -0,0 +1 @@
1
+ argx
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "argx"
3
+ version = "0.4.4"
4
+ description = "Super-charged argparse for python"
5
+ readme = "README.md"
6
+ license = {text = "MIT"}
7
+ requires-python = ">=3.9"
8
+ authors = [{name = "pwwang", email = "pwwang@pwwang.com"}]
9
+ dependencies = [
10
+ "python-simpleconf>=0.9,<1.0",
11
+ ]
12
+
13
+ [project.optional-dependencies]
14
+ anypath = ["panpath>=0.4,<0.5"]
15
+ panpath = ["panpath>=0.4,<0.5"]
16
+
17
+ [dependency-groups]
18
+ dev = [
19
+ "flake8>=7,<8",
20
+ "mypy>=1,<2",
21
+ "pytest>=8,<9",
22
+ "pytest-cov>=6,<7",
23
+ "python-simpleconf[toml]>=0.9,<1.0",
24
+ ]
25
+
26
+ [build-system]
27
+ requires = ["setuptools>=61"]
28
+ build-backend = "setuptools.build_meta"
29
+
30
+ [tool.setuptools.package-data]
31
+ argx = ["py.typed"]
32
+
33
+ [tool.mypy]
34
+ ignore_missing_imports = true
35
+ allow_redefinition = true
36
+ disable_error_code = ["attr-defined", "no-redef", "union-attr"]
37
+ show_error_codes = true
38
+ strict_optional = false
39
+
40
+ [tool.pytest.ini_options]
41
+ addopts = "-vv --cov-config=.coveragerc --cov=argx --cov-report xml:.coverage.xml --cov-report term-missing"
42
+ filterwarnings = [
43
+ #"error"
44
+ ]
45
+ console_output_style = "progress"
46
+ junit_family = "xunit1"
47
+
48
+ [tool.black]
49
+ line-length = 88
50
+ target-version = ['py39', 'py310', 'py311', 'py312']
51
+ include = '\.pyi?$'
argx-0.4.4/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
argx-0.4.4/setup.py ADDED
@@ -0,0 +1,14 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ This will not be included in the distribution.
4
+ The distribution metadata and dependencies are managed via pyproject.toml (uv).
5
+ This file is kept only for
6
+ 1. Github to index the dependents
7
+ 2. pip install -e .
8
+ Do NOT use this to install this package, unless you handled the dependencies
9
+ by your self:
10
+ pip install git+https://...
11
+ """
12
+ from setuptools import setup
13
+
14
+ setup(name="argx")
@@ -0,0 +1,259 @@
1
+ import pytest # noqa: F401
2
+ from argx import ArgumentParser
3
+ from argx.action import (
4
+ StoreAction,
5
+ StoreConstAction,
6
+ StoreTrueAction,
7
+ StoreFalseAction,
8
+ AppendAction,
9
+ AppendConstAction,
10
+ CountAction,
11
+ ExtendAction,
12
+ ClearExtendAction,
13
+ ClearAppendAction,
14
+ NamespaceAction,
15
+ )
16
+
17
+
18
+ def test_store():
19
+ parser = ArgumentParser()
20
+ parser.add_argument("--foo", action=StoreAction)
21
+ ns = parser.parse_args(["--foo", "bar"])
22
+ assert ns.foo == "bar"
23
+
24
+ parser.add_argument("--bar.baz", action=StoreAction)
25
+ ns = parser.parse_args(["--bar.baz", "qux"])
26
+ assert ns.bar.baz == "qux"
27
+
28
+
29
+ def test_store_const():
30
+ parser = ArgumentParser()
31
+ parser.add_argument("--foo", action=StoreConstAction, const="bar")
32
+ ns = parser.parse_args(["--foo"])
33
+ assert ns.foo == "bar"
34
+
35
+ parser.add_argument("--bar.baz", action=StoreConstAction, const="qux")
36
+ ns = parser.parse_args(["--bar.baz"])
37
+ assert ns.bar.baz == "qux"
38
+
39
+
40
+ def test_store_true():
41
+ parser = ArgumentParser()
42
+ parser.add_argument("--foo", action=StoreTrueAction)
43
+ ns = parser.parse_args(["--foo"])
44
+ assert ns.foo is True
45
+
46
+ parser.add_argument("--bar.baz", action=StoreTrueAction)
47
+ ns = parser.parse_args(["--bar.baz"])
48
+ assert ns.bar.baz is True
49
+
50
+
51
+ def test_store_false():
52
+ parser = ArgumentParser()
53
+ parser.add_argument("--foo", action=StoreFalseAction)
54
+ ns = parser.parse_args(["--foo"])
55
+ assert ns.foo is False
56
+
57
+ parser.add_argument("--bar.baz", action=StoreFalseAction)
58
+ ns = parser.parse_args(["--bar.baz"])
59
+ assert ns.bar.baz is False
60
+
61
+
62
+ def test_append():
63
+ parser = ArgumentParser()
64
+ parser.add_argument("--foo", action=AppendAction)
65
+ ns = parser.parse_args(["--foo", "bar"])
66
+ assert ns.foo == ["bar"]
67
+
68
+ parser.add_argument("--bar.baz", action=AppendAction)
69
+ ns = parser.parse_args(["--bar.baz", "qux"])
70
+ assert ns.bar.baz == ["qux"]
71
+
72
+
73
+ def test_append_const():
74
+ parser = ArgumentParser()
75
+ parser.add_argument("--foo", action=AppendConstAction, const="bar")
76
+ ns = parser.parse_args(["--foo"])
77
+ assert ns.foo == ["bar"]
78
+
79
+ parser.add_argument("--bar.baz", action=AppendConstAction, const="qux")
80
+ ns = parser.parse_args(["--bar.baz"])
81
+ assert ns.bar.baz == ["qux"]
82
+
83
+
84
+ def test_count():
85
+ parser = ArgumentParser()
86
+ parser.add_argument("--foo", action=CountAction)
87
+ ns = parser.parse_args(["--foo"])
88
+ assert ns.foo == 1
89
+
90
+ parser.add_argument("--bar.baz", action=CountAction)
91
+ ns = parser.parse_args(["--bar.baz"])
92
+ assert ns.bar.baz == 1
93
+
94
+ parser.add_argument("--bar.v", "-v", action=CountAction)
95
+ ns = parser.parse_args(["-vvv"])
96
+ assert ns.bar.v == 3
97
+
98
+
99
+ def test_extend():
100
+ parser = ArgumentParser()
101
+ parser.add_argument("--foo", nargs="+", action=ExtendAction)
102
+ ns = parser.parse_args(["--foo", "bar", "--foo", "baz", "qux"])
103
+ assert ns.foo == ["bar", "baz", "qux"]
104
+
105
+ parser.add_argument("--bar.baz", nargs="+", action=ExtendAction)
106
+ ns = parser.parse_args(["--bar.baz", "qux", "--bar.baz", "quux", "quuz"])
107
+ assert ns.bar.baz == ["qux", "quux", "quuz"]
108
+
109
+ parser.add_argument("--bar.v", "-v", nargs="+", action=ExtendAction)
110
+ ns = parser.parse_args(["-vvv"])
111
+ assert ns.bar.v == ["vv"]
112
+
113
+
114
+ def test_clear_append():
115
+ parser = ArgumentParser()
116
+ parser.add_argument("--foo", action=ClearAppendAction, default=["a"])
117
+ ns = parser.parse_args(["--foo", "bar", "--foo", "baz"])
118
+ assert ns.foo == ["bar", "baz"]
119
+
120
+ parser = ArgumentParser()
121
+ parser.add_argument("--foo", action="append", default=["a"])
122
+ ns = parser.parse_args(["--foo", "bar", "--foo", "baz"])
123
+ assert ns.foo == ["a", "bar", "baz"]
124
+
125
+ parser = ArgumentParser()
126
+ parser.add_argument("--bar.baz", action=ClearAppendAction, default=["a"])
127
+ ns = parser.parse_args(["--bar.baz", "qux", "--bar.baz", "quux"])
128
+ assert ns.bar.baz == ["qux", "quux"]
129
+
130
+ parser = ArgumentParser()
131
+ parser.add_argument("--bar.baz", action="append", default=["a"])
132
+ ns = parser.parse_args(["--bar.baz", "qux", "--bar.baz", "quux"])
133
+ assert ns.bar.baz == ["a", "qux", "quux"]
134
+
135
+ parser.add_argument("--bar.v", "-v", action=ClearAppendAction)
136
+ ns = parser.parse_args(["-vvv"])
137
+ assert ns.bar.v == ["vv"]
138
+
139
+
140
+ def test_clear_extend():
141
+ parser = ArgumentParser()
142
+ parser.add_argument(
143
+ "--foo",
144
+ nargs="+",
145
+ action=ClearExtendAction,
146
+ default=["a"],
147
+ )
148
+ ns = parser.parse_args(["--foo", "bar", "--foo", "baz", "qux"])
149
+ assert ns.foo == ["bar", "baz", "qux"]
150
+
151
+ parser = ArgumentParser()
152
+ parser.add_argument(
153
+ "--foo",
154
+ nargs="+",
155
+ action="extend",
156
+ default=["a"],
157
+ )
158
+ ns = parser.parse_args(["--foo", "bar", "--foo", "baz", "qux"])
159
+ assert ns.foo == ["a", "bar", "baz", "qux"]
160
+
161
+ parser = ArgumentParser()
162
+ parser.add_argument(
163
+ "--bar.baz",
164
+ nargs="+",
165
+ action=ClearExtendAction,
166
+ default=["a"],
167
+ )
168
+ ns = parser.parse_args(["--bar.baz", "qux", "--bar.baz", "quux", "quuz"])
169
+ assert ns.bar.baz == ["qux", "quux", "quuz"]
170
+
171
+ parser = ArgumentParser()
172
+ parser.add_argument(
173
+ "--bar.baz",
174
+ nargs="+",
175
+ action="extend",
176
+ default=["a"],
177
+ )
178
+ ns = parser.parse_args(["--bar.baz", "qux", "--bar.baz", "quux", "quuz"])
179
+ assert ns.bar.baz == ["a", "qux", "quux", "quuz"]
180
+
181
+ parser.add_argument("--bar.v", "-v", nargs="+", action=ClearExtendAction)
182
+ ns = parser.parse_args(["-vvv"])
183
+ assert ns.bar.v == ["vv"]
184
+
185
+
186
+ def test_namespace():
187
+ parser = ArgumentParser()
188
+ parser.add_argument("--foo", action=NamespaceAction)
189
+ parser.add_argument("--foo.bar", action=StoreAction)
190
+ parser.add_argument("--foo.ns", action=NamespaceAction)
191
+
192
+ ns = parser.parse_args(["--foo.bar", "baz"])
193
+ assert ns.foo.bar == "baz"
194
+
195
+ ns = parser.parse_args(
196
+ [
197
+ "--foo",
198
+ '{"bar": "cux", "d": "e", "ns": {"x": 1} }',
199
+ "--foo.bar",
200
+ "eux",
201
+ ]
202
+ )
203
+ assert ns.foo.bar == "eux"
204
+ assert ns.foo.d == "e"
205
+ assert ns.foo.ns.x == 1
206
+
207
+ with pytest.raises(SystemExit):
208
+ parser.parse_args(["--foo", "1"])
209
+
210
+ with pytest.raises(SystemExit):
211
+ parser.parse_args(["--foo", "{'a'}"])
212
+
213
+
214
+ def test_help():
215
+ parser = ArgumentParser()
216
+ parser.add_argument(
217
+ "--foo", action=StoreAction, help="foo help", show=False
218
+ )
219
+ help_str = parser.format_help()
220
+ assert "foo help" in help_str
221
+
222
+ parser = ArgumentParser(add_help="h,help,h+,help+")
223
+ parser.add_argument(
224
+ "--foo", action=StoreAction, help="foo help", show=False
225
+ )
226
+ help_str = parser.format_help()
227
+ assert "foo help" in help_str
228
+ help_str = parser.format_help(plus=False)
229
+ assert "foo help" not in help_str
230
+
231
+ parser = ArgumentParser(add_help="h,help,h+,help+")
232
+ parser.add_namespace("ns", show=False)
233
+ parser.add_argument("--ns.a", action=StoreAction, help="a help")
234
+ parser.add_argument("--ns.b", action=StoreAction, help="b help")
235
+ help_str = parser.format_help(plus=False)
236
+ assert "'ns'" not in help_str
237
+
238
+
239
+ def test_help_parse(capsys):
240
+ parser = ArgumentParser(add_help="h,help,h+,help+")
241
+ parser.add_namespace("ns", show=False)
242
+ parser.add_argument("--ns.a", action=StoreAction, help="a help")
243
+ parser.add_argument("--ns.b", action=StoreAction, help="b help")
244
+
245
+ with pytest.raises(SystemExit):
246
+ parser.parse_args(["--help+"])
247
+
248
+ assert "<ns>" in capsys.readouterr().out
249
+
250
+ parser = ArgumentParser()
251
+ parser.add_namespace("ns", show=False)
252
+ parser.add_argument("--ns.a", action=StoreAction, help="a help")
253
+ parser.add_argument("--ns.b", action=StoreAction, help="b help")
254
+
255
+ with pytest.raises(SystemExit):
256
+ parser.parse_args(["--help"])
257
+
258
+ # all options should be shown as no help + option is defined
259
+ assert "<ns>" in capsys.readouterr().out
@@ -0,0 +1,171 @@
1
+ import pytest # noqa: F401
2
+ from pathlib import Path
3
+ from argx import ArgumentParser
4
+
5
+
6
+ def test_exit_on_void():
7
+ parser = ArgumentParser(exit_on_void=False, fromfile_prefix_chars=None)
8
+ parser.add_argument("--foo", action="store_true", default=False)
9
+ ns = parser.parse_args([])
10
+ assert ns.foo is False
11
+
12
+ parser = ArgumentParser(exit_on_void=True)
13
+ parser.add_argument("--foo", action="store_true", default=False)
14
+ with pytest.raises(SystemExit):
15
+ parser.parse_args([])
16
+
17
+
18
+ def test_add_subparser_directly():
19
+ parser = ArgumentParser()
20
+ subparser_foo = parser.add_subparser("foo", help="The foo command")
21
+ subparser_bar = parser.add_subparser("bar")
22
+ assert "foo" in subparser_foo.prog
23
+ assert "bar" in subparser_bar.prog
24
+ help_str = parser.format_help()
25
+ assert "foo" in help_str
26
+ assert "The bar command" in help_str
27
+ assert " {foo,bar}" not in help_str
28
+
29
+ # by default, a command is required
30
+ with pytest.raises(SystemExit):
31
+ parser.parse_args([])
32
+
33
+
34
+ def test_namespace_options():
35
+ parser = ArgumentParser()
36
+ parser.add_argument("--foo.bar", action="store_true", default=False)
37
+ parser.add_argument("--foo.baz.qux", action="store_true", default=False)
38
+ parsed = parser.parse_args(["--foo.bar", "--foo.baz.qux"])
39
+ assert parsed.foo.bar is True
40
+ assert parsed.foo.baz.qux is True
41
+
42
+ help_str = parser.format_help()
43
+ assert "Namespace <foo>" in help_str
44
+
45
+ with pytest.raises(ValueError):
46
+ parser.add_namespace("foo")
47
+
48
+
49
+ def test_load_defaults_from_file():
50
+ defaultsfile = Path(__file__).parent / "configs" / "defaults.toml"
51
+ parser = ArgumentParser(fromfile_prefix_chars="@")
52
+ parser.add_argument("-a", required=True, type=int)
53
+ parser.add_argument("--ns.a-b", default=4, type=int)
54
+ command = parser.add_command("status")
55
+ command.add_argument("--branch")
56
+ parsed = parser.parse_args([f"@{defaultsfile}", "status"])
57
+ assert parsed.a == 1
58
+ assert parsed.branch == "dev"
59
+ assert getattr(parsed.ns, 'a-b') == 4
60
+
61
+ defaultspy = Path(__file__).parent / "configs" / "defaults.py"
62
+ parser = ArgumentParser(fromfile_prefix_chars="@")
63
+ parser.add_argument("--ns.v", required=True, type=int)
64
+ parser.add_argument("--ns.vv", required=True, type=int)
65
+ parsed = parser.parse_args([f"@{defaultspy}", "--ns.vv", "3"])
66
+ assert parsed.ns.v == 2
67
+ assert parsed.ns.vv == 3
68
+
69
+ bad_defaultspy = Path(__file__).parent / "configs" / "bad_defaults.py"
70
+ parser = ArgumentParser(fromfile_prefix_chars="@")
71
+ parser.add_argument("--ns.v", required=True, type=int)
72
+ with pytest.raises(SystemExit):
73
+ parser.parse_args([f"@{bad_defaultspy}"])
74
+
75
+
76
+ def test_load_from_config():
77
+ configfile = Path(__file__).parent / "configs" / "config.toml"
78
+ parser = ArgumentParser.from_configs(configfile, name="test_config")
79
+ parsed = parser.parse_args("-d -b 2 cmd1 cmd11 -f 1".split())
80
+ assert parsed.COMMAND == "cmd1"
81
+ assert parsed.COMMAND2 == "cmd11"
82
+
83
+ help_str = parser.format_help()
84
+ assert "test_config" in help_str
85
+ assert "Required Arguments" in help_str
86
+ assert (
87
+ help_str.find("Required Arguments")
88
+ < help_str.find("Option")
89
+ )
90
+ # The newlines and spaces kept
91
+ assert " - newline help" in help_str
92
+
93
+
94
+ def test_parse_known_args_parse_file_false():
95
+ parser = ArgumentParser(fromfile_prefix_chars="@")
96
+ parser.add_argument("-a", type=int)
97
+ parsed, argv = parser.parse_known_args(
98
+ ["@file.toml", "-a", "2"],
99
+ fromfile_parse=False,
100
+ fromfile_keep=True,
101
+ )
102
+ assert parsed.a == 2
103
+ assert argv == ["@file.toml"]
104
+
105
+
106
+ def test_parse_known_args_with_txt():
107
+ argsfile = Path(__file__).parent / "configs" / "args.txt"
108
+ parser = ArgumentParser(fromfile_prefix_chars="@")
109
+ parser.add_argument("-a", type=int)
110
+ parsed, argv = parser.parse_known_args(
111
+ [f"@{argsfile}", "-a", "2"],
112
+ fromfile_parse=False,
113
+ fromfile_keep=True,
114
+ )
115
+ assert parsed.a == 2
116
+ assert argv == ["-b", "3"]
117
+
118
+
119
+ def test_pre_parse_hook():
120
+ def pre_parse(parser, args, namespace):
121
+ parser.add_argument("--bar", required=True)
122
+ parser.add_argument("--a")
123
+ parser.add_argument("--b")
124
+ namespace.c = 3
125
+ return args + ["--a", "2"]
126
+
127
+ parser = ArgumentParser(pre_parse=pre_parse)
128
+ parsed = parser.parse_args(["--bar", "1"])
129
+ assert parsed.bar == "1"
130
+ assert parsed.a == "2"
131
+ assert parsed.c == 3
132
+
133
+
134
+ def test_pre_parse_hook_with_command():
135
+ def pre_parse(parser, args, namespace):
136
+ parser.add_argument("--bar", required=True)
137
+ parser.add_argument("--a")
138
+ parser.add_argument("--b")
139
+ namespace.c = 3
140
+ return args + ["--a", "2"]
141
+
142
+ parser = ArgumentParser()
143
+ parser.add_command("x", pre_parse=pre_parse)
144
+ parsed = parser.parse_args(["x", "--bar", "1"])
145
+ assert parsed.bar == "1"
146
+ assert parsed.a == "2"
147
+ assert parsed.c == 3
148
+
149
+
150
+ def test_different_help_option():
151
+ parser = ArgumentParser(add_help="help")
152
+ parser.add_argument("-h", required=True)
153
+ parsed = parser.parse_args(["-h", "1"])
154
+ assert parsed.h == "1"
155
+
156
+
157
+ def test_get_action():
158
+ parser = ArgumentParser()
159
+ parser.add_argument("--foo", action="store_true", default=False)
160
+ ns = parser.add_namespace("ns")
161
+ ns.add_argument("--bar", action="store_true", default=False)
162
+
163
+ ns_action = parser.get_action("ns", include_ns_group=True)
164
+ assert ns_action.name == "ns"
165
+
166
+ foo_action = parser.get_action("foo")
167
+ assert foo_action.default is False
168
+ bar_action = parser.get_action("bar")
169
+ assert bar_action.default is False
170
+
171
+ assert parser.get_action("baz") is None
@@ -0,0 +1,55 @@
1
+ import pytest # noqa: F401
2
+ from pathlib import Path
3
+ from argx import ArgumentParser
4
+ from panpath import S3Path
5
+
6
+
7
+ def test_py():
8
+ parser = ArgumentParser()
9
+ parser.add_argument("--foo", type="py")
10
+ ns = parser.parse_args(["--foo", "{'a': 1}"])
11
+ assert ns.foo == {"a": 1}
12
+
13
+
14
+ def test_json():
15
+ parser = ArgumentParser()
16
+ parser.add_argument("--foo", type="json")
17
+ ns = parser.parse_args(["--foo", '{"a": 1}'])
18
+ assert ns.foo == {"a": 1}
19
+
20
+
21
+ def test_auto():
22
+ parser = ArgumentParser()
23
+ parser.add_argument("--foo", type="auto")
24
+ ns = parser.parse_args(["--foo", '{"a": 1}'])
25
+ assert ns.foo == {"a": 1}
26
+
27
+ ns = parser.parse_args(["--foo", 'TRUE'])
28
+ assert ns.foo is True
29
+
30
+ ns = parser.parse_args(["--foo", 'FALSE'])
31
+ assert ns.foo is False
32
+
33
+ ns = parser.parse_args(["--foo", 'NONE'])
34
+ assert ns.foo is None
35
+
36
+ ns = parser.parse_args(["--foo", 'xy'])
37
+ assert ns.foo == 'xy'
38
+
39
+
40
+ def test_panpath():
41
+ parser = ArgumentParser()
42
+ parser.add_argument("--foo", type="panpath")
43
+ ns = parser.parse_args(["--foo", "s3://bucket/path"])
44
+ assert isinstance(ns.foo, S3Path)
45
+ assert str(ns.foo) == "s3://bucket/path"
46
+
47
+ ns = parser.parse_args(["--foo", "/local/path"])
48
+ assert isinstance(ns.foo, Path)
49
+ assert str(ns.foo) == "/local/path"
50
+
51
+
52
+ def test_unsupported_type():
53
+ parser = ArgumentParser()
54
+ with pytest.raises(ValueError, match="Invalid type"):
55
+ parser.add_argument("--foo", type="unsupported")
argx-0.4.2/pyproject.toml DELETED
@@ -1,48 +0,0 @@
1
- [tool.poetry]
2
- name = "argx"
3
- version = "0.4.2"
4
- description = "Super-charged argparse for python"
5
- authors = ["pwwang <pwwang@pwwang.com>"]
6
- license = "MIT"
7
- readme = "README.md"
8
-
9
- [tool.poetry.build]
10
- generate-setup-file = true
11
-
12
- [tool.poetry.dependencies]
13
- python = "^3.9"
14
- python-simpleconf = "^0.8"
15
- panpath = {version = "^0.4", optional = true}
16
-
17
- [tool.poetry.extras]
18
- anypath = ["panpath"]
19
- panpath = ["panpath"]
20
-
21
- [tool.poetry.group.dev.dependencies]
22
- pytest = "^8"
23
- pytest-cov = "^6"
24
- python-simpleconf = {version = "^0.8", extras = ["toml"]}
25
-
26
- [build-system]
27
- requires = ["poetry-core"]
28
- build-backend = "poetry.core.masonry.api"
29
-
30
- [tool.mypy]
31
- ignore_missing_imports = true
32
- allow_redefinition = true
33
- disable_error_code = ["attr-defined", "no-redef", "union-attr"]
34
- show_error_codes = true
35
- strict_optional = false
36
-
37
- [tool.pytest.ini_options]
38
- addopts = "-vv --cov-config=.coveragerc --cov=argx --cov-report xml:.coverage.xml --cov-report term-missing"
39
- filterwarnings = [
40
- #"error"
41
- ]
42
- console_output_style = "progress"
43
- junit_family = "xunit1"
44
-
45
- [tool.black]
46
- line-length = 88
47
- target-version = ['py37', 'py38', 'py39', 'py310', 'py311', 'py312']
48
- include = '\.pyi?$'
argx-0.4.2/setup.py DELETED
@@ -1,34 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from setuptools import setup
3
-
4
- packages = \
5
- ['argx']
6
-
7
- package_data = \
8
- {'': ['*']}
9
-
10
- install_requires = \
11
- ['python-simpleconf>=0.8,<0.9']
12
-
13
- extras_require = \
14
- {'anypath': ['panpath>=0.4,<0.5'], 'panpath': ['panpath>=0.4,<0.5']}
15
-
16
- setup_kwargs = {
17
- 'name': 'argx',
18
- 'version': '0.4.2',
19
- 'description': 'Super-charged argparse for python',
20
- 'long_description': '# argx\n\n[![pypi][1]][2] [![tag][3]][2] [![codacy quality][4]][5] [![codacy quality][6]][5] ![github action][7] ![pyver][8]\n\nSupercharged argparse for Python\n\n## Installation\n\n```bash\npip install -U argx\npip install -U argx[panpath] # to use panpath type\n# see https://github.com/pwwang/panpath\n```\n\n## Features enhanced or added\n\n- [Option `exit_on_void`](#option-exit_on_void): Exit with error if no arguments are provided\n- [Subcommand shortcut](#subcommand-shortcut): Adding subcommands directly, without `parser.add_subparsers()`\n- [Namespace arguments](#namespace-arguments): Access arguments like `--foo.bar` as `args.foo.bar`\n- [Brief help message for massive arguments](#brief-help-message-for-massive-arguments): Show only the most important arguments in the help message\n- [Default value in argument help](#default-value-in-argument-help): Show the default value in the help message of arguments\n- [Newlines kept in help](#newlines-kept-in-help): Newlines are kept in argument help if any\n- [Defaults from file](#defaults-from-files): Read default values from a configuration file by API or from command line\n- [Clear-append/extend action](#clear_appendextend-action): Store a list of values. Different from `append` and `extend`, the initial value is cleared.\n- [Grouping required arguments by default](#grouping-required-arguments-by-default): Put required arguments in \'required arguments\' group, instead of \'optional arguments\' group\n- [Order of groups in help message](#order-of-groups-in-help-message): Allow to add an `order` attribute to groups to change the order of groups in help message\n- [Additional types](#additional-types): Some additional types to convert the values of arguments\n- [Configuration file to create the parser](#configuration-file-to-create-the-parser): Instead of creating the parser by code, you can also create it by a configuration file\n- [API to get actions](#api-to-get-actions): Get the actions of the parser by API\n- [Pre-parse hook](#pre-parse-hook): A hook to modify the arguments before parsing\n- [Backward compatibility](#backward-compatibility): All features are optional. You can use `argx` as a drop-in replacement for `argparse`.\n\n### Option `exit_on_void`\n\nIf all arguments are optional, `argparse` will not raise an error if no arguments are provided. This is not always desirable. `argx` provides the option `exit_on_void` to change this behavior. If `exit_on_void` is set to `True` and no arguments are provided, `argx` will exit with an error (No arguments provided).\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser(exit_on_void=True)\nparser.add_argument(\'--foo\', action=\'store_true\')\n\nargs = parser.parse_args([])\n# No arguments provided\n# standard argparse produces: Namespace(foo=False)\n```\n\n### Subcommand shortcut\n\n`argparse` requires to create subparsers first and then add the subcommands to the subparsers.\n`argx` allows to add subcommands directly to the main parser.\n\n```python\n# standard argparse\nparser = argparse.ArgumentParser()\nsubparsers = parser.add_subparsers(title=\'subcommands\')\nparser_a = subparsers.add_parser(\'a\')\nparser_b = subparsers.add_parser(\'b\')\n\n# argx\nparser = argparse.ArgumentParser()\nparser.add_command(\'a\') # or parser.add_subparser(\'a\')\nparser.add_command(\'b\')\n# args = parser.parse_args([\'a\'])\n# Namespace(COMMAND=\'a\')\n```\n\nThe `subparsers` is added automatically with the title `subcommands` and the `dest` is set to `COMMAND`. You can add subcommands to subcommands directly, then the `dest` is set to `COMMAND2`, `COMMAND3`, etc. If you want to change the behavior, you can always fall back to the standard `argparse` way.\n\n### Namespace arguments\n\nThe values of arguments like `--foo.bar` can be accessed as `vars(args)[\'foo.bar\']`. With `argx` you can access them as `args.foo.bar`.\n\nThe arguments `--foo.bar`, `--foo.baz` and `--foo.qux` are automatically grouped in a namespace `foo`.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo.bar\', type=int)\nparser.add_argument(\'--foo.baz\', type=int)\nparser.add_argument(\'--foo.qux\', type=int)\n\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--foo.bar BAR] [--foo.baz BAZ] [--foo.qux QUX]\n\nOptional arguments:\n -h, --help show this help message and exit\n\nNamespace <foo>:\n --foo.bar BAR\n --foo.baz BAZ\n --foo.qux QUX\n```\n\nYou can modify the namespace by adding the namespace manually before adding the arguments.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_namespace(\'foo\', title="Foo\'s options")\nparser.add_argument(\'--foo.bar\', type=int)\nparser.add_argument(\'--foo.baz\', type=int)\nparser.add_argument(\'--foo.qux\', type=int)\n\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--foo.bar BAR] [--foo.baz BAZ] [--foo.qux QUX]\n\nOptional Arguments:\n -h, --help show this help message and exit\n\nFoo\'s Options:\n --foo.bar BAR\n --foo.baz BAZ\n --foo.qux QUX\n```\n\nYou can also add a namespace action argument to take a json that can be parsed as a dict:\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', action="namespace") # or action="ns"\nparser.add_argument(\'--foo.bar\', type=int)\nparser.add_argument(\'--foo.baz\', type=int)\nparser.add_argument(\'--foo.qux\', type=int)\n\nparser.parse_args([\'--foo\', \'{"bar": 1, "baz": 2, "qux": 3}\', \'--foo.qux\', \'4\'])\n# Namespace(foo=Namespace(bar=1, baz=2, qux=4))\n```\n\n### Brief help message for massive arguments\n\nIf you have a lot of arguments, the help message can be very long. `argx` allows to show only the most important arguments in the help message.\n\n```python\nimport argx as argparse\n\n# Advanced help options to show the brief help message or the full help message\nparser = argparse.ArgumentParser(add_help=\'h,help,h+,help+\')\nparser.add_argument(\'--foo\', type=int)\nparser.add_argument(\'--bar\', type=int, show=False)\nparser.parse_args([\'--help\'])\n```\n\n```shell\nUsage: test.py [-h] [--foo FOO]\n\nOptional Arguments:\n -h, --help, -h+, --help+\n show help message (with + to show more options) and exit\n --foo FOO\n```\n\nWith `parser.parse_args([\'--help+\'])` you can show the full help message.\n\n```shell\nUsage: test.py [-h] [--foo FOO] [--bar BAR]\n\nOptional Arguments:\n -h, --help, -h+, --help+\n show help message (with + to show more options) and exit\n --foo FOO\n --bar BAR\n```\n\nYou can also set `show=False` for argument groups.\n\n### Default value in argument help\n\nWith `argparse`, the default value is not shown in the help message. With `argx`, the default value is added to the help message automatically.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', type=int, default=1)\nparser.add_argument(\'--bar\', type=int, default=2, help=\'bar [default: two]\')\nparser.add_argument(\'--baz\', type=int, default=3, help=\'baz [nodefault]\')\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--foo FOO]\n\nOptional Arguments:\n -h, --help show help message and exit\n --foo FOO [default: 1]\n --bar BAR bar [default: two]\n --baz BAZ baz\n```\n\n### Newlines kept in help\n\nBy default, `argparse` replaces the newlines with spaces in the argument help message. However, sometimes you want to keep the newlines. With `argx`, if there is not newline, it is handled as the default behavior. If there is a newline, the newlines and spaces are kept.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', help=\'foo\\n- bar\\n indent also kept\')\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--foo FOO]\n\nOptional Arguments:\n -h, --help show this help message and exit\n --foo FOO foo\n - bar\n indent also kept\n```\n\n### Defaults from files\n\nWith standard `argparse`, when `fromfile_prefix_chars` is set, the arguments can be read from a file. The file can be specified with `@filename`. The arguments in the file are separated by newlines by default.\n\nWith `argx`, Other than a text file to provide command line arguments, you can also provide other types of configuration files. The extension of the file can be `.json`, `.yaml`, `.ini`, `.env` or `.toml`.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', type=int)\nparser.add_argument(\'--bar\', type=int)\nparser.add_argument(\'--baz\', type=int)\n\n# config.json\n# { "foo": 1, "bar": 2, "baz": 3 }\nargs = parser.parse_args([\'@config.json\'])\n# Namespace(foo=1, bar=2, baz=3)\n```\n\nYou can also use `set_defaults_from_configs` method:\n\n```python\nparser.set_defaults_from_configs(\'config.json\')\n```\n\n### Clear_append/extend action\n\nThe `clear_append`/`clear_extend` action is similar to `append` and `extend`, but the initial value is cleared.\n\nThis is useful when you want to accept a new list of values from the command line, instead of append/extend to the existing list or default.\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', action=\'clear_append\', default=[1, 2, 3], type=int)\nparser.add_argument(\'--bar\', action=\'append\', default=[1, 2, 3], type=int)\n\nargs = parser.parse_args(\'--foo 4 --foo 5 --bar 4 --bar 5\'.split())\n# Namespace(foo=[4, 5], bar=[1, 2, 3, 4, 5])\n```\n\n### Grouping required arguments by default\n\nBy default, `argparse` puts both `required=True` and `required=False` arguments in the same group (optional arguments), which is sometimes confusing. `argx` groups `required=True` arguments in a separate group (required arguments).\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\')\nparser.add_argument(\'--bar\', required=True)\n\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--foo FOO] --bar BAR\n\nRequired Arguments:\n --bar BAR\n\nOptional Arguments:\n -h, --help show help message and exit\n --foo FOO\n```\n\n### Order of groups in help message\n\nAllow to add an `order` attribute to groups to change the order of groups in help message\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\ngroup1 = parser.add_argument_group(\'group1\', order=2)\ngroup1.add_argument(\'--foo\')\ngroup2 = parser.add_argument_group(\'group2\', order=1)\ngroup2.add_argument(\'--bar\')\n\nparser.print_help()\n```\n\n```shell\nUsage: test.py [-h] [--bar BAR] [--foo FOO]\n\nOptional arguments:\n -h, --help show help message and exit\n\nGroup2:\n --bar BAR\n\nGroup1:\n --foo FOO\n```\n\nThe order by default is 0. The groups with the same order are sorted by title. Groups with small numbers are displayed first. `required arguments` has a `order` of -1.\n\n### Additional types\n\n`parser.add_argument()` accepts `type` as a function to convert the argument value. It has to be a callable that accepts a single string argument and returns the converted value. While `argx` supports string for `type` so it can be configured in the configuration file. Builtin functions and types can also be specified by its name.\n\nWe also have additional types:\n\n```python\nimport argx as argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\'--foo\', type=\'py\')\nparser.add_argument(\'--bar\', type=\'json\')\nparser.add_argument(\'--baz\', type=\'path\')\nparser.add_argument(\'--qux\', type=\'auto\')\nparser.add_argument(\'--quux\', type=\'panpath\') # requires panpath\n\nargs = parser.parse_args(\n \'--foo 1 --bar {"a":1} --baz path/to/file --qux true --quux s3://path/to\'.split()\n)\n# Namespace(\n# foo=1, bar={\'a\': 1}, baz=PosixPath(\'path/to/file\'),\n# qux=True, quux=S3Path(\'s3://path/to\')\n# )\n```\n\n- `py`: Python expression. The string is evaluated by `ast.literal_eval`.\n- `json`: JSON string. The string is loaded by `json.loads`.\n- `path`: Path string. The string is converted by `pathlib.Path`.\n- `auto`: Automatic type conversion.\n - `True` if the string is `True/TRUE/true`\n - `False` if the string is `False/FALSE/false`\n - `None` if the string is `None/NONE/none`\n - An integer if the string can be converted to an integer\n - A float if the string can be converted to a float\n - A dict if the string is a JSON string\n - The string itself otherwise\n\n### Configuration file to create the parser\n\nYou can create the parser from a configuration file.\n\n```python\nimport argx as argparse\n\n# config.json\n# {\n# "prog": "myprog",\n# "arguments": [ {"flags": ["-a", "--abc"], "help": "Optiona a help"} ]\n# }\nparser = argparse.ArgumentParser.from_configs(\'config.json\')\nparser.print_help()\n```\n\n```shell\nUsage: myprog [-h] [-a ABC]\n\nOptional Arguments:\n -h, --help show help message and exit\n -a ABC, --abc ABC Optiona a help\n```\n\n### API to get actions\n\nYou can get the actions of the parser by `.get_action()`.\n\n```python\nimport argx\n\nparser = argx.ArgumentParser()\nparser.add_argument(\'--foo\', type=int)\n\naction = parser.get_action(\'foo\')\n# StoreAction(option_strings=[\'--foo\'], dest=\'foo\', nargs=None, const=None,\n# default=None, type=<class \'int\'>, choices=None, required=False, help=None,\n# metavar=None)\n```\n\n### Pre-parse hook\n\nYou can add a pre-parse hook to the parser. The hook is called before parsing the arguments. It can be used to modify the arguments before parsing.\n\n```python\nimport argx as argparse\n\ndef pre_parse(parser, args, namespace):\n """We can modify the parser (i.e. add arguments)\n the arguments to be parsed, and even manipulate the namespace.\n """\n parser.add_argument(\'--foo\', type=int)\n parser.add_argument(\'--bar\', type=int)\n namespace.baz = 2\n return args + ["--bar", "3"]\n\nparser = argparse.ArgumentParser()\nparser.add_command(\'command1\', pre_parse=pre_parse)\nparsed = parser.parse_args(\'command1 --foo 1\'.split())\n# Namespace(COMMAND=\'command1\', baz=2, foo=1, bar=3)\n```\n\nThis is especially useful when you have a lot of subcommands and each has a lot of arguments, when it takes time to add these arguments, for example, some of the values need to be parsed from a file. Using this hook, you can add the arguments only when the subcommand is called, instead of adding them all at the beginning.\n\n### Backward compatibility\n\nAll features are optional. You can use `argx` as a drop-in replacement for `argparse`.\n\n`argx` supports python `3.7+`. Some of the later-introduced features are also supported in python 3.7. For example, `extend` action is added in python 3.8, `argx` supports in python 3.7.\n\n[1]: https://img.shields.io/pypi/v/argx.svg?style=flat-square\n[2]: https://pypi.org/project/argx/\n[3]: https://img.shields.io/github/tag/pwwang/argx.svg?style=flat-square\n[4]: https://img.shields.io/codacy/grade/c5eaafcde482437b901b1acd2b70420e.svg?style=flat-square\n[5]: https://app.codacy.com/gh/pwwang/argx/dashboard\n[6]: https://img.shields.io/codacy/coverage/c5eaafcde482437b901b1acd2b70420e.svg?style=flat-square\n[7]: https://img.shields.io/github/actions/workflow/status/pwwang/argx/build.yml?style=flat-square\n[8]: https://img.shields.io/pypi/pyversions/argx.svg?style=flat-square\n',
21
- 'author': 'pwwang',
22
- 'author_email': 'pwwang@pwwang.com',
23
- 'maintainer': 'None',
24
- 'maintainer_email': 'None',
25
- 'url': 'None',
26
- 'packages': packages,
27
- 'package_data': package_data,
28
- 'install_requires': install_requires,
29
- 'extras_require': extras_require,
30
- 'python_requires': '>=3.9,<4.0',
31
- }
32
-
33
-
34
- setup(**setup_kwargs)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes