calf 0.3.2__tar.gz → 0.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.
- calf-0.4/.gitignore +8 -0
- calf-0.4/PKG-INFO +173 -0
- {calf-0.3.2 → calf-0.4}/calf/__init__.py +57 -45
- {calf-0.3.2 → calf-0.4}/calf/__main__.py +1 -1
- calf-0.4/pyproject.toml +39 -0
- calf-0.4/requirements-dev.in +7 -0
- calf-0.4/tests/test_calf.py +256 -0
- calf-0.3.2/PKG-INFO +0 -170
- calf-0.3.2/calf.egg-info/PKG-INFO +0 -170
- calf-0.3.2/calf.egg-info/SOURCES.txt +0 -16
- calf-0.3.2/calf.egg-info/dependency_links.txt +0 -1
- calf-0.3.2/calf.egg-info/entry_points.txt +0 -3
- calf-0.3.2/calf.egg-info/top_level.txt +0 -1
- calf-0.3.2/setup.cfg +0 -4
- calf-0.3.2/setup.py +0 -33
- {calf-0.3.2 → calf-0.4}/LICENSE +0 -0
- {calf-0.3.2 → calf-0.4}/MANIFEST.in +0 -0
- {calf-0.3.2 → calf-0.4}/README.md +0 -0
- {calf-0.3.2 → calf-0.4}/calf/py.typed +0 -0
- {calf-0.3.2 → calf-0.4}/docs/design.md +0 -0
- {calf-0.3.2 → calf-0.4}/docs/examples/composite.py +0 -0
- {calf-0.3.2 → calf-0.4}/docs/examples/nextday.py +0 -0
- {calf-0.3.2 → calf-0.4}/docs/examples/simple.py +0 -0
calf-0.4/.gitignore
ADDED
calf-0.4/PKG-INFO
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: calf
|
|
3
|
+
Version: 0.4
|
|
4
|
+
Summary: Command Argument Loading Functions
|
|
5
|
+
Project-URL: Homepage, https://github.com/isaacto/calf
|
|
6
|
+
Project-URL: Repository, https://github.com/isaacto/calf.git
|
|
7
|
+
Project-URL: Issues, https://github.com/isaacto/calf/issues
|
|
8
|
+
Author-email: Isaac To <isaac.to@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# calf: Command Argument Loading Function for Python
|
|
25
|
+
|
|
26
|
+
Calf lets you remove all your command argument parsing code, at least
|
|
27
|
+
for simple cases. Only the implementation function is left, with
|
|
28
|
+
initialization code that uses calf to call this function. The command
|
|
29
|
+
argument parser is configured with a proper docstring, and perhaps
|
|
30
|
+
some annotations (argument type) and default values for the
|
|
31
|
+
parameters. In other words, stuffs that you would write anyway.
|
|
32
|
+
|
|
33
|
+
The docstring can be written in Google, Sphinx, epydoc or Numpy style,
|
|
34
|
+
and the design is that it is easy to swap the parsing function with
|
|
35
|
+
yours. In fact, you can customize such a wide range of
|
|
36
|
+
characteristics of calf, that you can treat it as a slightly
|
|
37
|
+
restricted frontend to the ArgumentParser under the hood. Used in
|
|
38
|
+
this way, you can treat calf as a cute way to configure argparse.
|
|
39
|
+
|
|
40
|
+
This package shamelessly stole a lot of ideas from
|
|
41
|
+
[plac](https://pypi.org/project/plac/), but hopes to be more focused
|
|
42
|
+
on creating comfortable command line interfaces rather than becoming a
|
|
43
|
+
Swiss knife for programs with text-only user interface.
|
|
44
|
+
|
|
45
|
+
## Basic example
|
|
46
|
+
|
|
47
|
+
Hello-world looks like this:
|
|
48
|
+
|
|
49
|
+
def hello(name) -> None:
|
|
50
|
+
"""Say hello
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
|
|
54
|
+
name: name of to say hello to
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
print('Hello,', name)
|
|
58
|
+
|
|
59
|
+
if __name__ == '__main__':
|
|
60
|
+
import calf
|
|
61
|
+
calf.call(hello)
|
|
62
|
+
|
|
63
|
+
The first thing to notice is that the program uses Google docstring
|
|
64
|
+
style. If you want to use another style, just add
|
|
65
|
+
`doc_parser=<parser>` to `calf.call`. Here `<parser>` may be
|
|
66
|
+
`calf.google_doc_parser`, `calf.sphinx_doc_parser` (for Sphinx or
|
|
67
|
+
Epydoc) or `calf.numpy_doc_parser`. You can run this program with:
|
|
68
|
+
|
|
69
|
+
hello.py Isaac
|
|
70
|
+
|
|
71
|
+
Here `name` is a positional command line argument: a normal function
|
|
72
|
+
argument always maps to a positional command line argument. If you
|
|
73
|
+
want an option instead, you can replace the function argument like
|
|
74
|
+
this:
|
|
75
|
+
|
|
76
|
+
def hello(*, name: str = 'Isaac') -> None:
|
|
77
|
+
"""Say hello
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
|
|
81
|
+
name: (-n) name of to say hello to
|
|
82
|
+
|
|
83
|
+
"""
|
|
84
|
+
print('Hello,', name)
|
|
85
|
+
|
|
86
|
+
Then the program is run like one of the following:
|
|
87
|
+
|
|
88
|
+
hello.py
|
|
89
|
+
hello.py --name Cathy
|
|
90
|
+
hello.py -n Cathy
|
|
91
|
+
|
|
92
|
+
Now `name` is an option: a keyword-only function argument always maps
|
|
93
|
+
to a function. In this version we are explicit about the type of the
|
|
94
|
+
argument. Note also that the leading `-n` in the docstring describing
|
|
95
|
+
the argument, enclosed in parentheses, becomes the short option name.
|
|
96
|
+
|
|
97
|
+
It is usually a good idea to allow options not to be specified, by
|
|
98
|
+
providing a default value. Positional arguments can also be provided
|
|
99
|
+
a default value, but it doesn't mix well with variable arguments
|
|
100
|
+
described below.
|
|
101
|
+
|
|
102
|
+
It is also possible to specify a default which provides no value (so
|
|
103
|
+
the program knows that no value is provide). This is done by either
|
|
104
|
+
using a default value of None, or setting in parameter a type of a
|
|
105
|
+
parameterized Typing.Optional (without setting a default). In this
|
|
106
|
+
case the normal construction of the target type will not happen.
|
|
107
|
+
|
|
108
|
+
There is a special case: any boolean function argument becomes a
|
|
109
|
+
default-off flag. I cannot find a natural way to have a default-on
|
|
110
|
+
flag, so it is not provided. (Let me know if you think otherwise!)
|
|
111
|
+
|
|
112
|
+
Variable arguments and keyword arguments can also be used. Variable
|
|
113
|
+
arguments will become a list of the specified type:
|
|
114
|
+
|
|
115
|
+
def do_sum(*arg: int) -> None:
|
|
116
|
+
"""Sum numbers"""
|
|
117
|
+
print('Sum =', sum(arg, 0))
|
|
118
|
+
|
|
119
|
+
Here the argument type is "int". The string passed in the command
|
|
120
|
+
line argument will be converted to this type, and in the help message
|
|
121
|
+
there will be a little hint (looking like "[int]") indicating the
|
|
122
|
+
needed type. Also note that in this example I don't add documentation
|
|
123
|
+
for the arguments: the docstring information is optional, without them
|
|
124
|
+
there is no help string but everything else still works.
|
|
125
|
+
|
|
126
|
+
Keyword arguments cause command line arguments like "<name>=<value>"
|
|
127
|
+
to be stolen from the var-arg and form a map. A type can still be
|
|
128
|
+
provided. For example, if you have:
|
|
129
|
+
|
|
130
|
+
import urllib.parse
|
|
131
|
+
def get_query_str(url, **item) -> None:
|
|
132
|
+
"Create URL with parameters"
|
|
133
|
+
qstr = urllib.parse.urlencode(item)
|
|
134
|
+
if qstr:
|
|
135
|
+
url += '?' + qstr
|
|
136
|
+
print(url)
|
|
137
|
+
|
|
138
|
+
Then you can run something like
|
|
139
|
+
|
|
140
|
+
get_query_str.py http://a/b x=a=c y=/
|
|
141
|
+
|
|
142
|
+
to get `http://a/b?y=%2F&x=a%3Dc`.
|
|
143
|
+
|
|
144
|
+
Finally, if you're tired of writing initialization code, you have an
|
|
145
|
+
additional option to directly place your module under your
|
|
146
|
+
PYTHONPATH. Then you can run your program simply like
|
|
147
|
+
|
|
148
|
+
calf hello.hello -n Isaac
|
|
149
|
+
|
|
150
|
+
## Advanced capability
|
|
151
|
+
|
|
152
|
+
You can have your function to accept other types. Calf normally uses
|
|
153
|
+
one positional argument or option for each function argument, and
|
|
154
|
+
whatever string you specified in the argument will be passed to the
|
|
155
|
+
type you specified (via default argument or annotation) as
|
|
156
|
+
constructor. In cases that passing the string to the type constructor
|
|
157
|
+
doesn't do the right thing (e.g., `datetime`), you can create your own
|
|
158
|
+
conversion function and add it to calf.CONVERTERS. This has been done
|
|
159
|
+
for `datetime.date`, `datetime.time` and `datetime.datetime`, and you
|
|
160
|
+
can change how they behave by modifying `calf.CONVERTERS` (see the
|
|
161
|
+
`nextday.py` example in the docs directory).
|
|
162
|
+
|
|
163
|
+
But you can also extend calf by creating a subclass of "selector" which
|
|
164
|
+
selects function arguments based on name and type. It then specifies
|
|
165
|
+
how to create a "loader" to handle the function argument, which may
|
|
166
|
+
use multiple command line arguments (or do any other interaction with
|
|
167
|
+
the ArgumentParser). See `composite.py` in the docs directory to see
|
|
168
|
+
how this is done, for the common case.
|
|
169
|
+
|
|
170
|
+
Other parts of the module can also be overridden. For example, you
|
|
171
|
+
can change the docstring parser and parameter doc parser. See the
|
|
172
|
+
design document in the docs directory to understand the design and do
|
|
173
|
+
all sorts of things with calf.
|
|
@@ -19,6 +19,9 @@ import sys
|
|
|
19
19
|
import typing
|
|
20
20
|
|
|
21
21
|
|
|
22
|
+
__version__ = '0.4'
|
|
23
|
+
|
|
24
|
+
|
|
22
25
|
ConverterType = typing.Callable[[str], typing.Any]
|
|
23
26
|
|
|
24
27
|
|
|
@@ -36,27 +39,27 @@ def _datetime_convert(s: str) -> datetime.datetime:
|
|
|
36
39
|
return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
|
|
37
40
|
|
|
38
41
|
|
|
39
|
-
CONVERTERS = {
|
|
42
|
+
CONVERTERS: dict[type, ConverterType] = {
|
|
40
43
|
datetime.date: lambda s: datetime.datetime.strptime(s, '%Y-%m-%d').date(),
|
|
41
44
|
datetime.time: _time_convert,
|
|
42
45
|
datetime.datetime: _datetime_convert,
|
|
43
|
-
}
|
|
46
|
+
}
|
|
44
47
|
"Add or change a function here if you want to teach calf how to read a type"
|
|
45
48
|
|
|
46
49
|
|
|
47
50
|
class ParamInfo:
|
|
48
51
|
"Parameter information extracted from doc-strings"
|
|
49
52
|
def __init__(self, desc: str, short: str = '',
|
|
50
|
-
choices: typing.Optional[
|
|
53
|
+
choices: typing.Optional[list[str]] = None) -> None:
|
|
51
54
|
self.desc = desc
|
|
52
55
|
"The description of the parameter"
|
|
53
56
|
self.short = short
|
|
54
57
|
"The short option string, like '-i'"
|
|
55
|
-
self.choices
|
|
58
|
+
self.choices: typing.Optional[list[str]] = choices
|
|
56
59
|
"The possible choices"
|
|
57
60
|
|
|
58
61
|
|
|
59
|
-
DocParserRetType =
|
|
62
|
+
DocParserRetType = tuple[str, dict[str, ParamInfo]]
|
|
60
63
|
DocParserType = typing.Callable[[str], DocParserRetType]
|
|
61
64
|
|
|
62
65
|
|
|
@@ -165,7 +168,7 @@ def numpy_doc_parser(doc: str) -> DocParserRetType:
|
|
|
165
168
|
return main_doc, param_docs
|
|
166
169
|
|
|
167
170
|
|
|
168
|
-
def indented_groups(inp: str) -> typing.Iterator[
|
|
171
|
+
def indented_groups(inp: str) -> typing.Iterator[list[str]]:
|
|
169
172
|
"""Split text according to indentation
|
|
170
173
|
|
|
171
174
|
Args:
|
|
@@ -370,8 +373,7 @@ class CalfRunner:
|
|
|
370
373
|
|
|
371
374
|
def ns2params(self, calf_info: 'CalfInfo',
|
|
372
375
|
namespace: argparse.Namespace) \
|
|
373
|
-
->
|
|
374
|
-
typing.Dict[str, typing.Any]]:
|
|
376
|
+
-> tuple[list[typing.Any], dict[str, typing.Any]]:
|
|
375
377
|
"""Construct parameter from namespace
|
|
376
378
|
|
|
377
379
|
The conversion information is used to convert namespace
|
|
@@ -388,8 +390,8 @@ class CalfRunner:
|
|
|
388
390
|
The positional and keyword arguments for calling the function
|
|
389
391
|
|
|
390
392
|
"""
|
|
391
|
-
pos
|
|
392
|
-
kwd
|
|
393
|
+
pos: list[typing.Any] = []
|
|
394
|
+
kwd: dict[str, typing.Any] = {}
|
|
393
395
|
for loader in calf_info.arg_loaders.values():
|
|
394
396
|
loader.load(namespace, pos, kwd)
|
|
395
397
|
return pos, kwd
|
|
@@ -468,7 +470,7 @@ class BaseArgLoader:
|
|
|
468
470
|
self._param = param
|
|
469
471
|
self._ptype = ptype
|
|
470
472
|
if type(self._ptype) == type(typing.Optional[int]): # noqa, type-check
|
|
471
|
-
pargs = typing.cast(typing.Optional[
|
|
473
|
+
pargs = typing.cast(typing.Optional[tuple[typing.Any, ...]],
|
|
472
474
|
getattr(self._ptype, '__args__'))
|
|
473
475
|
if pargs and len(pargs) == 2 \
|
|
474
476
|
and pargs[1] == type(None): # noqa, type-check
|
|
@@ -488,9 +490,9 @@ class BaseArgLoader:
|
|
|
488
490
|
"""
|
|
489
491
|
raise NotImplementedError()
|
|
490
492
|
|
|
491
|
-
def basic_arg_extra(self) ->
|
|
493
|
+
def basic_arg_extra(self) -> dict[str, typing.Any]:
|
|
492
494
|
"Get basic argument extra parameters"
|
|
493
|
-
extra
|
|
495
|
+
extra: dict[str, typing.Any] = {}
|
|
494
496
|
if self._default is not NO_DEFAULT:
|
|
495
497
|
extra['default'] = self._default
|
|
496
498
|
if self._info:
|
|
@@ -499,12 +501,11 @@ class BaseArgLoader:
|
|
|
499
501
|
extra['choices'] = self._info.choices
|
|
500
502
|
if self._ptype is not str:
|
|
501
503
|
extra['help'] = '%s [%s]' % (extra.get('help', ''),
|
|
502
|
-
self._ptype
|
|
504
|
+
_gettype(self._ptype))
|
|
503
505
|
return extra
|
|
504
506
|
|
|
505
507
|
def load(self, namespace: argparse.Namespace,
|
|
506
|
-
pos: typing.
|
|
507
|
-
kwd: typing.Dict[str, typing.Any]) -> None:
|
|
508
|
+
pos: list[typing.Any], kwd: dict[str, typing.Any]) -> None:
|
|
508
509
|
"""Populate parameters for calling the target function
|
|
509
510
|
|
|
510
511
|
Args:
|
|
@@ -525,10 +526,9 @@ class BaseArgLoader:
|
|
|
525
526
|
|
|
526
527
|
"""
|
|
527
528
|
try:
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
self._ptype))(val)
|
|
529
|
+
ptype = _gettype(self._ptype)
|
|
530
|
+
return val if val is None else \
|
|
531
|
+
CONVERTERS.get(ptype, typing.cast(ConverterType, ptype))(val)
|
|
532
532
|
except ValueError:
|
|
533
533
|
print('Error: Value "%s" cannot be converted to type %s'
|
|
534
534
|
% (val, self._ptype.__name__), file=sys.stderr)
|
|
@@ -557,11 +557,28 @@ class PosArgLoader(BaseArgLoader):
|
|
|
557
557
|
calf_info.parser.add_argument(*names, **extra)
|
|
558
558
|
|
|
559
559
|
def load(self, namespace: argparse.Namespace,
|
|
560
|
-
pos: typing.
|
|
561
|
-
kwd: typing.Dict[str, typing.Any]) -> None:
|
|
560
|
+
pos: list[typing.Any], kwd: dict[str, typing.Any]) -> None:
|
|
562
561
|
pos.append(self.conv(getattr(namespace, self._param)))
|
|
563
562
|
|
|
564
563
|
|
|
564
|
+
def _gettype(ptype: typing.Type[typing.Any]) -> typing.Type[typing.Any]:
|
|
565
|
+
if type(ptype).__name__ != 'UnionType':
|
|
566
|
+
return ptype
|
|
567
|
+
return getinnertype(ptype, ptype.__args__) # pragma: no cover
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def getinnertype(
|
|
571
|
+
ptype: typing.Type[typing.Any], ptypes: list[typing.Type[typing.Any]]
|
|
572
|
+
) -> typing.Type[typing.Any]:
|
|
573
|
+
found: list[typing.Type[typing.Any]] = []
|
|
574
|
+
for parg in ptypes:
|
|
575
|
+
if parg is not type(None):
|
|
576
|
+
found.append(parg)
|
|
577
|
+
if len(found) != 1:
|
|
578
|
+
raise RuntimeError('calf: Type %s not supported', ptype)
|
|
579
|
+
return found[0]
|
|
580
|
+
|
|
581
|
+
|
|
565
582
|
class OptArgLoader(BaseArgLoader):
|
|
566
583
|
"Define how to handle an option"
|
|
567
584
|
|
|
@@ -584,8 +601,7 @@ class OptArgLoader(BaseArgLoader):
|
|
|
584
601
|
calf_info.parser.add_argument(*names, **extra)
|
|
585
602
|
|
|
586
603
|
def load(self, namespace: argparse.Namespace,
|
|
587
|
-
pos: typing.
|
|
588
|
-
kwd: typing.Dict[str, typing.Any]) -> None:
|
|
604
|
+
pos: list[typing.Any], kwd: dict[str, typing.Any]) -> None:
|
|
589
605
|
kwd[self._param] = self.conv(getattr(namespace, self._param))
|
|
590
606
|
|
|
591
607
|
|
|
@@ -593,7 +609,7 @@ class VarArgLoader(BaseArgLoader):
|
|
|
593
609
|
"Define how to handle a basic remaining option"
|
|
594
610
|
|
|
595
611
|
def prepare(self, calf_info: 'CalfInfo') -> None:
|
|
596
|
-
extra = {'nargs': '*'}
|
|
612
|
+
extra: dict[str, typing.Any] = {'nargs': '*'}
|
|
597
613
|
if self._info:
|
|
598
614
|
extra['help'] = self._info.desc
|
|
599
615
|
calf_info.var_arg_broker.register_var('', self._param)
|
|
@@ -601,8 +617,7 @@ class VarArgLoader(BaseArgLoader):
|
|
|
601
617
|
calf_info.parser.add_argument(self._param, **extra)
|
|
602
618
|
|
|
603
619
|
def load(self, namespace: argparse.Namespace,
|
|
604
|
-
pos: typing.
|
|
605
|
-
kwd: typing.Dict[str, typing.Any]) -> None:
|
|
620
|
+
pos: list[typing.Any], kwd: dict[str, typing.Any]) -> None:
|
|
606
621
|
pos.extend(self.conv(val)
|
|
607
622
|
for val in getattr(namespace, self._param))
|
|
608
623
|
|
|
@@ -611,8 +626,7 @@ class MapArgLoader(BaseArgLoader):
|
|
|
611
626
|
"Define how to handle a map-like remaining option"
|
|
612
627
|
|
|
613
628
|
def prepare(self, calf_info: 'CalfInfo') -> None:
|
|
614
|
-
extra = {'nargs': '*',
|
|
615
|
-
'metavar': 'key=val'} # type: typing.Dict[str, typing.Any]
|
|
629
|
+
extra: dict[str, typing.Any] = {'nargs': '*', 'metavar': 'key=val'}
|
|
616
630
|
if self._info:
|
|
617
631
|
extra['help'] = self._info.desc
|
|
618
632
|
calf_info.var_arg_broker.register_var(
|
|
@@ -621,8 +635,7 @@ class MapArgLoader(BaseArgLoader):
|
|
|
621
635
|
calf_info.parser.add_argument(self._param, **extra)
|
|
622
636
|
|
|
623
637
|
def load(self, namespace: argparse.Namespace,
|
|
624
|
-
pos: typing.
|
|
625
|
-
kwd: typing.Dict[str, typing.Any]) -> None:
|
|
638
|
+
pos: list[typing.Any], kwd: dict[str, typing.Any]) -> None:
|
|
626
639
|
for pval in getattr(namespace, self._param):
|
|
627
640
|
key, _, mval = pval.partition('=')
|
|
628
641
|
kwd[key] = self.conv(mval)
|
|
@@ -633,7 +646,7 @@ class CompositeArgLoader(BaseArgLoader):
|
|
|
633
646
|
info: typing.Optional[ParamInfo],
|
|
634
647
|
default: typing.Any,
|
|
635
648
|
ctor: FuncType,
|
|
636
|
-
subloaders:
|
|
649
|
+
subloaders: list[BaseArgLoader]) -> None:
|
|
637
650
|
super().__init__(param, ptype, info, default)
|
|
638
651
|
self._ctor = ctor
|
|
639
652
|
self._subloaders = subloaders
|
|
@@ -643,23 +656,23 @@ class CompositeArgLoader(BaseArgLoader):
|
|
|
643
656
|
loader.prepare(calf_info)
|
|
644
657
|
|
|
645
658
|
def load(self, namespace: argparse.Namespace,
|
|
646
|
-
pos:
|
|
647
|
-
kwd:
|
|
648
|
-
vararg
|
|
649
|
-
varkw
|
|
659
|
+
pos: list[typing.Any],
|
|
660
|
+
kwd: dict[str, typing.Any]) -> None:
|
|
661
|
+
vararg: list[typing.Any] = []
|
|
662
|
+
varkw: dict[str, typing.Any] = {}
|
|
650
663
|
for loader in self._subloaders:
|
|
651
664
|
loader.load(namespace, vararg, varkw)
|
|
652
665
|
pos.append(self._ctor(*vararg, **varkw))
|
|
653
666
|
|
|
654
667
|
|
|
655
668
|
VarIdentType = typing.Union[str, typing.Pattern[str]]
|
|
656
|
-
BrokerTupleType =
|
|
669
|
+
BrokerTupleType = tuple[VarIdentType, str]
|
|
657
670
|
|
|
658
671
|
|
|
659
672
|
class VarArgBroker:
|
|
660
673
|
"Configure how remaining arguments are distributed among namespace"
|
|
661
674
|
def __init__(self) -> None:
|
|
662
|
-
self._registered
|
|
675
|
+
self._registered: list[BrokerTupleType] = []
|
|
663
676
|
|
|
664
677
|
def register_var(self, var_ident: VarIdentType, param: str) -> None:
|
|
665
678
|
"""Register a request to remaining argument
|
|
@@ -685,7 +698,7 @@ class VarArgBroker:
|
|
|
685
698
|
return bool(var_ident.match(pval))
|
|
686
699
|
|
|
687
700
|
def distribute(self, namespace: argparse.Namespace,
|
|
688
|
-
others:
|
|
701
|
+
others: list[str]) -> None:
|
|
689
702
|
"""Distribute variable length arguments among namespace records
|
|
690
703
|
|
|
691
704
|
Collect the variable length argument, and look for a
|
|
@@ -720,13 +733,12 @@ class CalfInfo:
|
|
|
720
733
|
"Conversion information"
|
|
721
734
|
def __init__(self) -> None:
|
|
722
735
|
self.usage = ''
|
|
723
|
-
self.param_specs
|
|
724
|
-
self.param_info
|
|
725
|
-
self.arg_loaders = collections.OrderedDict(
|
|
726
|
-
) # type: typing.Dict[str, BaseArgLoader]
|
|
736
|
+
self.param_specs: typing.Optional[inspect.FullArgSpec] = None
|
|
737
|
+
self.param_info: dict[str, ParamInfo] = {}
|
|
738
|
+
self.arg_loaders: dict[str, BaseArgLoader] = collections.OrderedDict()
|
|
727
739
|
self.var_arg_broker = VarArgBroker()
|
|
728
|
-
self.parser
|
|
729
|
-
self.namespace
|
|
740
|
+
self.parser: typing.Optional[argparse.ArgumentParser] = None
|
|
741
|
+
self.namespace: typing.Optional[argparse.Namespace] = None
|
|
730
742
|
|
|
731
743
|
|
|
732
744
|
def call(func: typing.Callable[..., typing.Any],
|
|
@@ -7,7 +7,7 @@ import typing
|
|
|
7
7
|
import calf
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
def main(argv: typing.Optional[
|
|
10
|
+
def main(argv: typing.Optional[list[str]] = None) -> None:
|
|
11
11
|
"The main function for your function"
|
|
12
12
|
args = (sys.argv if argv is None else argv)[1:]
|
|
13
13
|
fullname = args.pop(0)
|
calf-0.4/pyproject.toml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
dynamic = ["version"]
|
|
7
|
+
name = "calf"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">= 3.9"
|
|
10
|
+
authors = [
|
|
11
|
+
{ name="Isaac To", email="isaac.to@gmail.com" },
|
|
12
|
+
]
|
|
13
|
+
description = "Command Argument Loading Functions"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
classifiers=[
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Topic :: Software Development :: Libraries",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Operating System :: OS Independent",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
console_scripts = "calf:__main__"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/isaacto/calf"
|
|
34
|
+
Repository = "https://github.com/isaacto/calf.git"
|
|
35
|
+
Issues = "https://github.com/isaacto/calf/issues"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.version]
|
|
38
|
+
source = "regex"
|
|
39
|
+
path = "calf/__init__.py"
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import datetime
|
|
3
|
+
import collections
|
|
4
|
+
import typing
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
import calf
|
|
9
|
+
import calf.__main__ as cm
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def func0a() -> str:
|
|
13
|
+
return 'hello'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_degenerated_a():
|
|
17
|
+
assert calf.call(func0a, []), 'hello'
|
|
18
|
+
assert calf.call(func0a, [], doc_parser=calf.sphinx_doc_parser), 'hello'
|
|
19
|
+
assert calf.call(func0a, [], doc_parser=calf.numpy_doc_parser), 'hello'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def func0b() -> str:
|
|
23
|
+
"""func0b
|
|
24
|
+
|
|
25
|
+
Say hello
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
|
|
29
|
+
Constant value 'hello'
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
return 'hello'
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_degenerated_b(capsys):
|
|
36
|
+
assert calf.call(func0b, []), 'hello'
|
|
37
|
+
with pytest.raises(SystemExit):
|
|
38
|
+
calf.call(func0b, ['-h'])
|
|
39
|
+
captured = capsys.readouterr()
|
|
40
|
+
assert 'Say hello' in captured.out
|
|
41
|
+
assert 'Constant' not in captured.out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def func0c() -> str:
|
|
45
|
+
"""func0c
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
|
|
49
|
+
"""
|
|
50
|
+
return 'hello'
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_degenerated_c(capsys):
|
|
54
|
+
assert calf.call(func0c, []), 'hello'
|
|
55
|
+
with pytest.raises(SystemExit):
|
|
56
|
+
calf.call(func0c, ['-h'])
|
|
57
|
+
captured = capsys.readouterr()
|
|
58
|
+
assert 'func0c' in captured.out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def func1(var1: int, var2: bool, *, var3: str, var4: str='bar') \
|
|
62
|
+
-> typing.Tuple[int, bool, str, str]:
|
|
63
|
+
"""Test function
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
var1: Variable 1
|
|
67
|
+
var2: (-f) Variable 2
|
|
68
|
+
var3: (-x) Variable 3
|
|
69
|
+
var4: (-v) Variable 4 {foo, bar, baz}
|
|
70
|
+
|
|
71
|
+
"""
|
|
72
|
+
return var1, var2, var3, var4
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def func1s(var1: int, var2: bool, *, var3: str, var4: str='bar') \
|
|
76
|
+
-> typing.Tuple[int, bool, str, str]:
|
|
77
|
+
"""Test function
|
|
78
|
+
|
|
79
|
+
:param var1: Variable 1
|
|
80
|
+
:param var2: (-f) Variable 2
|
|
81
|
+
:param var3: (-x) Variable 3
|
|
82
|
+
:param var4: (-v) Variable 4 {foo, bar, baz}
|
|
83
|
+
:other: other
|
|
84
|
+
|
|
85
|
+
"""
|
|
86
|
+
return var1, var2, var3, var4
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def func1n(var1: int, var2: bool, *, var3: str, var4: str='bar') \
|
|
90
|
+
-> typing.Tuple[int, bool, str, str]:
|
|
91
|
+
"""Test function
|
|
92
|
+
|
|
93
|
+
Parameter
|
|
94
|
+
---------
|
|
95
|
+
var1
|
|
96
|
+
Variable 1
|
|
97
|
+
var2 :
|
|
98
|
+
(-f) Variable 2
|
|
99
|
+
var3:
|
|
100
|
+
(-x) Variable 3
|
|
101
|
+
var4 : str
|
|
102
|
+
(-v) Variable 4 {foo, bar, baz}
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
|
|
107
|
+
Nothing
|
|
108
|
+
|
|
109
|
+
"""
|
|
110
|
+
return var1, var2, var3, var4
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def func1d(var1: datetime.date, var2: datetime.time, var3: datetime.datetime) \
|
|
114
|
+
-> typing.Tuple[datetime.date, datetime.time, datetime.datetime]:
|
|
115
|
+
return var1, var2, var3
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_help(capsys):
|
|
119
|
+
with pytest.raises(SystemExit):
|
|
120
|
+
calf.call(func1, ['-h'])
|
|
121
|
+
captured = capsys.readouterr()
|
|
122
|
+
assert ' -f, ' in captured.out
|
|
123
|
+
with pytest.raises(SystemExit):
|
|
124
|
+
calf.call(func1s, ['-h'], doc_parser=calf.sphinx_doc_parser)
|
|
125
|
+
captured = capsys.readouterr()
|
|
126
|
+
assert ' -f, ' in captured.out
|
|
127
|
+
with pytest.raises(SystemExit):
|
|
128
|
+
calf.call(func1n, ['-h'], doc_parser=calf.numpy_doc_parser)
|
|
129
|
+
captured = capsys.readouterr()
|
|
130
|
+
assert ' -f, ' in captured.out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_simple(capsys):
|
|
134
|
+
assert calf.call(func1, ['12', '--var3', 'x']) == (12, False, 'x', 'bar')
|
|
135
|
+
assert calf.call(
|
|
136
|
+
func1, ['12', '-f', '-v', 'foo', '-x', '5']) == (12, True, '5', 'foo')
|
|
137
|
+
with pytest.raises(SystemExit):
|
|
138
|
+
calf.call(func1, ['x', '--var3', 'x'])
|
|
139
|
+
captured = capsys.readouterr()
|
|
140
|
+
assert 'cannot be converted' in captured.err
|
|
141
|
+
assert calf.call(func1d, ['2020-03-15', '22:30', '2020-03-15T22:30']) \
|
|
142
|
+
== (datetime.date(2020, 3, 15),
|
|
143
|
+
datetime.time(22, 30),
|
|
144
|
+
datetime.datetime(2020, 3, 15, 22, 30))
|
|
145
|
+
assert calf.call(
|
|
146
|
+
func1d, ['2020-03-15', '22:30:15', '2020-03-15T22:30:15']) \
|
|
147
|
+
== (datetime.date(2020, 3, 15),
|
|
148
|
+
datetime.time(22, 30, 15),
|
|
149
|
+
datetime.datetime(2020, 3, 15, 22, 30, 15))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def func2(*args, **kwargs: str) -> typing.Tuple[ # type: ignore
|
|
153
|
+
typing.List[str], typing.Dict[str, str]]:
|
|
154
|
+
"""Test vararg function
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
args: Var args
|
|
158
|
+
kwargs: Keyword args
|
|
159
|
+
|
|
160
|
+
"""
|
|
161
|
+
return args, kwargs
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_varargs():
|
|
165
|
+
assert calf.call(func2, ['foo', 'bar']) == (('foo', 'bar'), {})
|
|
166
|
+
assert calf.call(func2, ['foo1=bar', 'foo2=baz']) \
|
|
167
|
+
== ((), {'foo1': 'bar', 'foo2': 'baz'})
|
|
168
|
+
assert calf.call(func2, ['foo', 'foo1=bar', 'bar']) \
|
|
169
|
+
== (('foo', 'bar'), {'foo1': 'bar'})
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def func3(var1: int, var2: typing.Optional[int],
|
|
173
|
+
var3: str = 'foo') -> typing.Tuple[int, str]:
|
|
174
|
+
"""Test function
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
var1: Variable 1
|
|
178
|
+
var2: Variable 2
|
|
179
|
+
var3: Variable 3
|
|
180
|
+
|
|
181
|
+
"""
|
|
182
|
+
return var1, var2, var3
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_pos_default():
|
|
186
|
+
assert calf.call(func3, ['42', '15', 'bar']) == (42, 15, 'bar')
|
|
187
|
+
assert calf.call(func3, ['42']) == (42, None, 'foo')
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def func4(**kwargs: str) -> typing.Dict[str, str]:
|
|
191
|
+
"""Test function
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
kwargs: Kwd
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
return kwargs
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_kwargs_only():
|
|
201
|
+
assert calf.call(func4, ['bar=42']) == {'bar': '42'}
|
|
202
|
+
with pytest.raises(ValueError):
|
|
203
|
+
calf.call(func4, ['bar'])
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
Name = collections.namedtuple('Name', ['firstname', 'lastname'])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def func5(name: Name):
|
|
210
|
+
return(name)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class NameSelector(calf.LoaderSelector):
|
|
214
|
+
def match(self, param: str, ptype: type, kind: str,
|
|
215
|
+
info: typing.Optional[calf.ParamInfo]) -> bool:
|
|
216
|
+
return ptype == Name
|
|
217
|
+
|
|
218
|
+
def make_loader(self, param: str, ptype: type, kind: str,
|
|
219
|
+
info: typing.Optional[calf.ParamInfo],
|
|
220
|
+
default: typing.Any) -> calf.BaseArgLoader:
|
|
221
|
+
return calf.CompositeArgLoader(
|
|
222
|
+
param, ptype, info, default, Name,
|
|
223
|
+
[calf.OptArgLoader('firstname', str,
|
|
224
|
+
calf.ParamInfo('First name', '-f'), 'Isaac'),
|
|
225
|
+
calf.OptArgLoader('lastname', str,
|
|
226
|
+
calf.ParamInfo('Last name', '-l'), 'To')])
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def test_composite():
|
|
230
|
+
assert calf.CalfRunner(
|
|
231
|
+
[NameSelector()],
|
|
232
|
+
doc_parser=calf.google_doc_parser,
|
|
233
|
+
param_parser=calf.basic_param_parser)(func5, []) == Name('Isaac', 'To')
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def test_unimplemented():
|
|
237
|
+
base_loader = calf.BaseArgLoader('p1', str, None, calf.NO_DEFAULT)
|
|
238
|
+
calf_info = calf.CalfInfo()
|
|
239
|
+
with pytest.raises(NotImplementedError):
|
|
240
|
+
base_loader.prepare(calf_info)
|
|
241
|
+
with pytest.raises(NotImplementedError):
|
|
242
|
+
base_loader.load(argparse.Namespace(), [], {})
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def test_getinner():
|
|
246
|
+
with pytest.raises(RuntimeError):
|
|
247
|
+
calf.getinnertype(type(None), [])
|
|
248
|
+
with pytest.raises(RuntimeError):
|
|
249
|
+
calf.getinnertype(type(None), [int, str])
|
|
250
|
+
assert calf.getinnertype(type(None), [int, type(None)]) is int
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_main():
|
|
254
|
+
cm.main(['test_calf', 'test_calf.func0a'])
|
|
255
|
+
with pytest.raises(SystemExit):
|
|
256
|
+
cm.main(['test_calf', '-h'])
|
calf-0.3.2/PKG-INFO
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: calf
|
|
3
|
-
Version: 0.3.2
|
|
4
|
-
Summary: Command Argument Loading Functions
|
|
5
|
-
Home-page: https://github.com/isaacto/calf
|
|
6
|
-
Author: Isaac To
|
|
7
|
-
Author-email: isaac.to@gmail.com
|
|
8
|
-
License: UNKNOWN
|
|
9
|
-
Description: # calf: Command Argument Loading Function for Python
|
|
10
|
-
|
|
11
|
-
Calf lets you remove all your command argument parsing code, at least
|
|
12
|
-
for simple cases. Only the implementation function is left, with
|
|
13
|
-
initialization code that uses calf to call this function. The command
|
|
14
|
-
argument parser is configured with a proper docstring, and perhaps
|
|
15
|
-
some annotations (argument type) and default values for the
|
|
16
|
-
parameters. In other words, stuffs that you would write anyway.
|
|
17
|
-
|
|
18
|
-
The docstring can be written in Google, Sphinx, epydoc or Numpy style,
|
|
19
|
-
and the design is that it is easy to swap the parsing function with
|
|
20
|
-
yours. In fact, you can customize such a wide range of
|
|
21
|
-
characteristics of calf, that you can treat it as a slightly
|
|
22
|
-
restricted frontend to the ArgumentParser under the hood. Used in
|
|
23
|
-
this way, you can treat calf as a cute way to configure argparse.
|
|
24
|
-
|
|
25
|
-
This package shamelessly stole a lot of ideas from
|
|
26
|
-
[plac](https://pypi.org/project/plac/), but hopes to be more focused
|
|
27
|
-
on creating comfortable command line interfaces rather than becoming a
|
|
28
|
-
Swiss knife for programs with text-only user interface.
|
|
29
|
-
|
|
30
|
-
## Basic example
|
|
31
|
-
|
|
32
|
-
Hello-world looks like this:
|
|
33
|
-
|
|
34
|
-
def hello(name) -> None:
|
|
35
|
-
"""Say hello
|
|
36
|
-
|
|
37
|
-
Args:
|
|
38
|
-
|
|
39
|
-
name: name of to say hello to
|
|
40
|
-
|
|
41
|
-
"""
|
|
42
|
-
print('Hello,', name)
|
|
43
|
-
|
|
44
|
-
if __name__ == '__main__':
|
|
45
|
-
import calf
|
|
46
|
-
calf.call(hello)
|
|
47
|
-
|
|
48
|
-
The first thing to notice is that the program uses Google docstring
|
|
49
|
-
style. If you want to use another style, just add
|
|
50
|
-
`doc_parser=<parser>` to `calf.call`. Here `<parser>` may be
|
|
51
|
-
`calf.google_doc_parser`, `calf.sphinx_doc_parser` (for Sphinx or
|
|
52
|
-
Epydoc) or `calf.numpy_doc_parser`. You can run this program with:
|
|
53
|
-
|
|
54
|
-
hello.py Isaac
|
|
55
|
-
|
|
56
|
-
Here `name` is a positional command line argument: a normal function
|
|
57
|
-
argument always maps to a positional command line argument. If you
|
|
58
|
-
want an option instead, you can replace the function argument like
|
|
59
|
-
this:
|
|
60
|
-
|
|
61
|
-
def hello(*, name: str = 'Isaac') -> None:
|
|
62
|
-
"""Say hello
|
|
63
|
-
|
|
64
|
-
Args:
|
|
65
|
-
|
|
66
|
-
name: (-n) name of to say hello to
|
|
67
|
-
|
|
68
|
-
"""
|
|
69
|
-
print('Hello,', name)
|
|
70
|
-
|
|
71
|
-
Then the program is run like one of the following:
|
|
72
|
-
|
|
73
|
-
hello.py
|
|
74
|
-
hello.py --name Cathy
|
|
75
|
-
hello.py -n Cathy
|
|
76
|
-
|
|
77
|
-
Now `name` is an option: a keyword-only function argument always maps
|
|
78
|
-
to a function. In this version we are explicit about the type of the
|
|
79
|
-
argument. Note also that the leading `-n` in the docstring describing
|
|
80
|
-
the argument, enclosed in parentheses, becomes the short option name.
|
|
81
|
-
|
|
82
|
-
It is usually a good idea to allow options not to be specified, by
|
|
83
|
-
providing a default value. Positional arguments can also be provided
|
|
84
|
-
a default value, but it doesn't mix well with variable arguments
|
|
85
|
-
described below.
|
|
86
|
-
|
|
87
|
-
It is also possible to specify a default which provides no value (so
|
|
88
|
-
the program knows that no value is provide). This is done by either
|
|
89
|
-
using a default value of None, or setting in parameter a type of a
|
|
90
|
-
parameterized Typing.Optional (without setting a default). In this
|
|
91
|
-
case the normal construction of the target type will not happen.
|
|
92
|
-
|
|
93
|
-
There is a special case: any boolean function argument becomes a
|
|
94
|
-
default-off flag. I cannot find a natural way to have a default-on
|
|
95
|
-
flag, so it is not provided. (Let me know if you think otherwise!)
|
|
96
|
-
|
|
97
|
-
Variable arguments and keyword arguments can also be used. Variable
|
|
98
|
-
arguments will become a list of the specified type:
|
|
99
|
-
|
|
100
|
-
def do_sum(*arg: int) -> None:
|
|
101
|
-
"""Sum numbers"""
|
|
102
|
-
print('Sum =', sum(arg, 0))
|
|
103
|
-
|
|
104
|
-
Here the argument type is "int". The string passed in the command
|
|
105
|
-
line argument will be converted to this type, and in the help message
|
|
106
|
-
there will be a little hint (looking like "[int]") indicating the
|
|
107
|
-
needed type. Also note that in this example I don't add documentation
|
|
108
|
-
for the arguments: the docstring information is optional, without them
|
|
109
|
-
there is no help string but everything else still works.
|
|
110
|
-
|
|
111
|
-
Keyword arguments cause command line arguments like "<name>=<value>"
|
|
112
|
-
to be stolen from the var-arg and form a map. A type can still be
|
|
113
|
-
provided. For example, if you have:
|
|
114
|
-
|
|
115
|
-
import urllib.parse
|
|
116
|
-
def get_query_str(url, **item) -> None:
|
|
117
|
-
"Create URL with parameters"
|
|
118
|
-
qstr = urllib.parse.urlencode(item)
|
|
119
|
-
if qstr:
|
|
120
|
-
url += '?' + qstr
|
|
121
|
-
print(url)
|
|
122
|
-
|
|
123
|
-
Then you can run something like
|
|
124
|
-
|
|
125
|
-
get_query_str.py http://a/b x=a=c y=/
|
|
126
|
-
|
|
127
|
-
to get `http://a/b?y=%2F&x=a%3Dc`.
|
|
128
|
-
|
|
129
|
-
Finally, if you're tired of writing initialization code, you have an
|
|
130
|
-
additional option to directly place your module under your
|
|
131
|
-
PYTHONPATH. Then you can run your program simply like
|
|
132
|
-
|
|
133
|
-
calf hello.hello -n Isaac
|
|
134
|
-
|
|
135
|
-
## Advanced capability
|
|
136
|
-
|
|
137
|
-
You can have your function to accept other types. Calf normally uses
|
|
138
|
-
one positional argument or option for each function argument, and
|
|
139
|
-
whatever string you specified in the argument will be passed to the
|
|
140
|
-
type you specified (via default argument or annotation) as
|
|
141
|
-
constructor. In cases that passing the string to the type constructor
|
|
142
|
-
doesn't do the right thing (e.g., `datetime`), you can create your own
|
|
143
|
-
conversion function and add it to calf.CONVERTERS. This has been done
|
|
144
|
-
for `datetime.date`, `datetime.time` and `datetime.datetime`, and you
|
|
145
|
-
can change how they behave by modifying `calf.CONVERTERS` (see the
|
|
146
|
-
`nextday.py` example in the docs directory).
|
|
147
|
-
|
|
148
|
-
But you can also extend calf by creating a subclass of "selector" which
|
|
149
|
-
selects function arguments based on name and type. It then specifies
|
|
150
|
-
how to create a "loader" to handle the function argument, which may
|
|
151
|
-
use multiple command line arguments (or do any other interaction with
|
|
152
|
-
the ArgumentParser). See `composite.py` in the docs directory to see
|
|
153
|
-
how this is done, for the common case.
|
|
154
|
-
|
|
155
|
-
Other parts of the module can also be overridden. For example, you
|
|
156
|
-
can change the docstring parser and parameter doc parser. See the
|
|
157
|
-
design document in the docs directory to understand the design and do
|
|
158
|
-
all sorts of things with calf.
|
|
159
|
-
|
|
160
|
-
Platform: UNKNOWN
|
|
161
|
-
Classifier: Development Status :: 4 - Beta
|
|
162
|
-
Classifier: Programming Language :: Python :: 3.5
|
|
163
|
-
Classifier: Programming Language :: Python :: 3.6
|
|
164
|
-
Classifier: Programming Language :: Python :: 3.7
|
|
165
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
166
|
-
Classifier: Topic :: Software Development :: Libraries
|
|
167
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
168
|
-
Classifier: Operating System :: OS Independent
|
|
169
|
-
Requires-Python: ~=3.5
|
|
170
|
-
Description-Content-Type: text/markdown
|
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: calf
|
|
3
|
-
Version: 0.3.2
|
|
4
|
-
Summary: Command Argument Loading Functions
|
|
5
|
-
Home-page: https://github.com/isaacto/calf
|
|
6
|
-
Author: Isaac To
|
|
7
|
-
Author-email: isaac.to@gmail.com
|
|
8
|
-
License: UNKNOWN
|
|
9
|
-
Description: # calf: Command Argument Loading Function for Python
|
|
10
|
-
|
|
11
|
-
Calf lets you remove all your command argument parsing code, at least
|
|
12
|
-
for simple cases. Only the implementation function is left, with
|
|
13
|
-
initialization code that uses calf to call this function. The command
|
|
14
|
-
argument parser is configured with a proper docstring, and perhaps
|
|
15
|
-
some annotations (argument type) and default values for the
|
|
16
|
-
parameters. In other words, stuffs that you would write anyway.
|
|
17
|
-
|
|
18
|
-
The docstring can be written in Google, Sphinx, epydoc or Numpy style,
|
|
19
|
-
and the design is that it is easy to swap the parsing function with
|
|
20
|
-
yours. In fact, you can customize such a wide range of
|
|
21
|
-
characteristics of calf, that you can treat it as a slightly
|
|
22
|
-
restricted frontend to the ArgumentParser under the hood. Used in
|
|
23
|
-
this way, you can treat calf as a cute way to configure argparse.
|
|
24
|
-
|
|
25
|
-
This package shamelessly stole a lot of ideas from
|
|
26
|
-
[plac](https://pypi.org/project/plac/), but hopes to be more focused
|
|
27
|
-
on creating comfortable command line interfaces rather than becoming a
|
|
28
|
-
Swiss knife for programs with text-only user interface.
|
|
29
|
-
|
|
30
|
-
## Basic example
|
|
31
|
-
|
|
32
|
-
Hello-world looks like this:
|
|
33
|
-
|
|
34
|
-
def hello(name) -> None:
|
|
35
|
-
"""Say hello
|
|
36
|
-
|
|
37
|
-
Args:
|
|
38
|
-
|
|
39
|
-
name: name of to say hello to
|
|
40
|
-
|
|
41
|
-
"""
|
|
42
|
-
print('Hello,', name)
|
|
43
|
-
|
|
44
|
-
if __name__ == '__main__':
|
|
45
|
-
import calf
|
|
46
|
-
calf.call(hello)
|
|
47
|
-
|
|
48
|
-
The first thing to notice is that the program uses Google docstring
|
|
49
|
-
style. If you want to use another style, just add
|
|
50
|
-
`doc_parser=<parser>` to `calf.call`. Here `<parser>` may be
|
|
51
|
-
`calf.google_doc_parser`, `calf.sphinx_doc_parser` (for Sphinx or
|
|
52
|
-
Epydoc) or `calf.numpy_doc_parser`. You can run this program with:
|
|
53
|
-
|
|
54
|
-
hello.py Isaac
|
|
55
|
-
|
|
56
|
-
Here `name` is a positional command line argument: a normal function
|
|
57
|
-
argument always maps to a positional command line argument. If you
|
|
58
|
-
want an option instead, you can replace the function argument like
|
|
59
|
-
this:
|
|
60
|
-
|
|
61
|
-
def hello(*, name: str = 'Isaac') -> None:
|
|
62
|
-
"""Say hello
|
|
63
|
-
|
|
64
|
-
Args:
|
|
65
|
-
|
|
66
|
-
name: (-n) name of to say hello to
|
|
67
|
-
|
|
68
|
-
"""
|
|
69
|
-
print('Hello,', name)
|
|
70
|
-
|
|
71
|
-
Then the program is run like one of the following:
|
|
72
|
-
|
|
73
|
-
hello.py
|
|
74
|
-
hello.py --name Cathy
|
|
75
|
-
hello.py -n Cathy
|
|
76
|
-
|
|
77
|
-
Now `name` is an option: a keyword-only function argument always maps
|
|
78
|
-
to a function. In this version we are explicit about the type of the
|
|
79
|
-
argument. Note also that the leading `-n` in the docstring describing
|
|
80
|
-
the argument, enclosed in parentheses, becomes the short option name.
|
|
81
|
-
|
|
82
|
-
It is usually a good idea to allow options not to be specified, by
|
|
83
|
-
providing a default value. Positional arguments can also be provided
|
|
84
|
-
a default value, but it doesn't mix well with variable arguments
|
|
85
|
-
described below.
|
|
86
|
-
|
|
87
|
-
It is also possible to specify a default which provides no value (so
|
|
88
|
-
the program knows that no value is provide). This is done by either
|
|
89
|
-
using a default value of None, or setting in parameter a type of a
|
|
90
|
-
parameterized Typing.Optional (without setting a default). In this
|
|
91
|
-
case the normal construction of the target type will not happen.
|
|
92
|
-
|
|
93
|
-
There is a special case: any boolean function argument becomes a
|
|
94
|
-
default-off flag. I cannot find a natural way to have a default-on
|
|
95
|
-
flag, so it is not provided. (Let me know if you think otherwise!)
|
|
96
|
-
|
|
97
|
-
Variable arguments and keyword arguments can also be used. Variable
|
|
98
|
-
arguments will become a list of the specified type:
|
|
99
|
-
|
|
100
|
-
def do_sum(*arg: int) -> None:
|
|
101
|
-
"""Sum numbers"""
|
|
102
|
-
print('Sum =', sum(arg, 0))
|
|
103
|
-
|
|
104
|
-
Here the argument type is "int". The string passed in the command
|
|
105
|
-
line argument will be converted to this type, and in the help message
|
|
106
|
-
there will be a little hint (looking like "[int]") indicating the
|
|
107
|
-
needed type. Also note that in this example I don't add documentation
|
|
108
|
-
for the arguments: the docstring information is optional, without them
|
|
109
|
-
there is no help string but everything else still works.
|
|
110
|
-
|
|
111
|
-
Keyword arguments cause command line arguments like "<name>=<value>"
|
|
112
|
-
to be stolen from the var-arg and form a map. A type can still be
|
|
113
|
-
provided. For example, if you have:
|
|
114
|
-
|
|
115
|
-
import urllib.parse
|
|
116
|
-
def get_query_str(url, **item) -> None:
|
|
117
|
-
"Create URL with parameters"
|
|
118
|
-
qstr = urllib.parse.urlencode(item)
|
|
119
|
-
if qstr:
|
|
120
|
-
url += '?' + qstr
|
|
121
|
-
print(url)
|
|
122
|
-
|
|
123
|
-
Then you can run something like
|
|
124
|
-
|
|
125
|
-
get_query_str.py http://a/b x=a=c y=/
|
|
126
|
-
|
|
127
|
-
to get `http://a/b?y=%2F&x=a%3Dc`.
|
|
128
|
-
|
|
129
|
-
Finally, if you're tired of writing initialization code, you have an
|
|
130
|
-
additional option to directly place your module under your
|
|
131
|
-
PYTHONPATH. Then you can run your program simply like
|
|
132
|
-
|
|
133
|
-
calf hello.hello -n Isaac
|
|
134
|
-
|
|
135
|
-
## Advanced capability
|
|
136
|
-
|
|
137
|
-
You can have your function to accept other types. Calf normally uses
|
|
138
|
-
one positional argument or option for each function argument, and
|
|
139
|
-
whatever string you specified in the argument will be passed to the
|
|
140
|
-
type you specified (via default argument or annotation) as
|
|
141
|
-
constructor. In cases that passing the string to the type constructor
|
|
142
|
-
doesn't do the right thing (e.g., `datetime`), you can create your own
|
|
143
|
-
conversion function and add it to calf.CONVERTERS. This has been done
|
|
144
|
-
for `datetime.date`, `datetime.time` and `datetime.datetime`, and you
|
|
145
|
-
can change how they behave by modifying `calf.CONVERTERS` (see the
|
|
146
|
-
`nextday.py` example in the docs directory).
|
|
147
|
-
|
|
148
|
-
But you can also extend calf by creating a subclass of "selector" which
|
|
149
|
-
selects function arguments based on name and type. It then specifies
|
|
150
|
-
how to create a "loader" to handle the function argument, which may
|
|
151
|
-
use multiple command line arguments (or do any other interaction with
|
|
152
|
-
the ArgumentParser). See `composite.py` in the docs directory to see
|
|
153
|
-
how this is done, for the common case.
|
|
154
|
-
|
|
155
|
-
Other parts of the module can also be overridden. For example, you
|
|
156
|
-
can change the docstring parser and parameter doc parser. See the
|
|
157
|
-
design document in the docs directory to understand the design and do
|
|
158
|
-
all sorts of things with calf.
|
|
159
|
-
|
|
160
|
-
Platform: UNKNOWN
|
|
161
|
-
Classifier: Development Status :: 4 - Beta
|
|
162
|
-
Classifier: Programming Language :: Python :: 3.5
|
|
163
|
-
Classifier: Programming Language :: Python :: 3.6
|
|
164
|
-
Classifier: Programming Language :: Python :: 3.7
|
|
165
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
166
|
-
Classifier: Topic :: Software Development :: Libraries
|
|
167
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
168
|
-
Classifier: Operating System :: OS Independent
|
|
169
|
-
Requires-Python: ~=3.5
|
|
170
|
-
Description-Content-Type: text/markdown
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
LICENSE
|
|
2
|
-
MANIFEST.in
|
|
3
|
-
README.md
|
|
4
|
-
setup.py
|
|
5
|
-
calf/__init__.py
|
|
6
|
-
calf/__main__.py
|
|
7
|
-
calf/py.typed
|
|
8
|
-
calf.egg-info/PKG-INFO
|
|
9
|
-
calf.egg-info/SOURCES.txt
|
|
10
|
-
calf.egg-info/dependency_links.txt
|
|
11
|
-
calf.egg-info/entry_points.txt
|
|
12
|
-
calf.egg-info/top_level.txt
|
|
13
|
-
docs/design.md
|
|
14
|
-
docs/examples/composite.py
|
|
15
|
-
docs/examples/nextday.py
|
|
16
|
-
docs/examples/simple.py
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
calf
|
calf-0.3.2/setup.cfg
DELETED
calf-0.3.2/setup.py
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import setuptools
|
|
2
|
-
|
|
3
|
-
with open('README.md', 'r') as fh:
|
|
4
|
-
long_description = fh.read()
|
|
5
|
-
|
|
6
|
-
setuptools.setup(
|
|
7
|
-
name='calf',
|
|
8
|
-
version='0.3.2',
|
|
9
|
-
python_requires='~=3.5',
|
|
10
|
-
author='Isaac To',
|
|
11
|
-
author_email='isaac.to@gmail.com',
|
|
12
|
-
description='Command Argument Loading Functions',
|
|
13
|
-
long_description=long_description,
|
|
14
|
-
long_description_content_type='text/markdown',
|
|
15
|
-
url='https://github.com/isaacto/calf',
|
|
16
|
-
packages=setuptools.find_packages(),
|
|
17
|
-
entry_points={
|
|
18
|
-
"console_scripts": [
|
|
19
|
-
"calf=calf.__main__:main",
|
|
20
|
-
]
|
|
21
|
-
},
|
|
22
|
-
package_data={'calf': ['py.typed']},
|
|
23
|
-
classifiers=[
|
|
24
|
-
'Development Status :: 4 - Beta',
|
|
25
|
-
'Programming Language :: Python :: 3.5',
|
|
26
|
-
'Programming Language :: Python :: 3.6',
|
|
27
|
-
'Programming Language :: Python :: 3.7',
|
|
28
|
-
'Programming Language :: Python :: 3.8',
|
|
29
|
-
'Topic :: Software Development :: Libraries',
|
|
30
|
-
'License :: OSI Approved :: MIT License',
|
|
31
|
-
'Operating System :: OS Independent',
|
|
32
|
-
],
|
|
33
|
-
)
|
{calf-0.3.2 → calf-0.4}/LICENSE
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|