Skip to content

Commit 8e7bed0

Browse files
authored
Break up arguments section (#2586)
2 parents bed0377 + 3241541 commit 8e7bed0

File tree

5 files changed

+164
-176
lines changed

5 files changed

+164
-176
lines changed

docs/arguments.rst

Lines changed: 64 additions & 172 deletions
Original file line numberDiff line numberDiff line change
@@ -5,195 +5,118 @@ Arguments
55

66
.. currentmodule:: click
77

8-
Arguments work similarly to :ref:`options <options>` but are positional.
9-
They also only support a subset of the features of options due to their
10-
syntactical nature. Click will also not attempt to document arguments for
11-
you and wants you to :ref:`document them manually <documenting-arguments>`
12-
in order to avoid ugly help pages.
8+
Arguments are:
9+
10+
* Are positional in nature.
11+
* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs
12+
* :ref:`Documented manually <documenting-arguments>`.
13+
14+
Useful and often used kwargs are:
15+
16+
* ``default``: Passes a default.
17+
* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.
1318

1419
Basic Arguments
1520
---------------
1621

17-
The most basic option is a simple string argument of one value. If no
18-
type is provided, the type of the default value is used, and if no default
19-
value is provided, the type is assumed to be :data:`STRING`.
22+
A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.
2023

2124
Example:
2225

2326
.. click:example::
2427
2528
@click.command()
2629
@click.argument('filename')
27-
def touch(filename):
30+
def touch(filename: str):
2831
"""Print FILENAME."""
2932
click.echo(filename)
3033

31-
And what it looks like:
34+
And from the command line:
3235

3336
.. click:run::
3437
3538
invoke(touch, args=['foo.txt'])
3639

37-
Variadic Arguments
38-
------------------
3940

40-
The second most common version is variadic arguments where a specific (or
41-
unlimited) number of arguments is accepted. This can be controlled with
42-
the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number
43-
of arguments is accepted.
41+
An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.
4442

45-
The value is then passed as a tuple. Note that only one argument can be
46-
set to ``nargs=-1``, as it will eat up all arguments.
43+
.. admonition:: Note on Required Arguments
4744

48-
Example:
45+
It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.
46+
47+
Multiple Arguments
48+
-----------------------------------
49+
50+
To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.
4951

5052
.. click:example::
5153
5254
@click.command()
53-
@click.argument('src', nargs=-1)
54-
@click.argument('dst', nargs=1)
55-
def copy(src, dst):
55+
@click.argument('src', nargs=1)
56+
@click.argument('dsts', nargs=-1)
57+
def copy(src: str, dsts: tuple[str, ...]):
5658
"""Move file SRC to DST."""
57-
for fn in src:
58-
click.echo(f"move {fn} to folder {dst}")
59+
for destination in dsts:
60+
click.echo(f"Copy {src} to folder {destination}")
5961

60-
And what it looks like:
62+
And from the command line:
6163

6264
.. click:run::
6365
64-
invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])
65-
66-
Note that this is not how you would write this application. The reason
67-
for this is that in this particular example the arguments are defined as
68-
strings. Filenames, however, are not strings! They might be on certain
69-
operating systems, but not necessarily on all. For better ways to write
70-
this, see the next sections.
66+
invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])
7167

72-
.. admonition:: Note on Non-Empty Variadic Arguments
68+
.. admonition:: Note on Handling Files
7369

74-
If you come from ``argparse``, you might be missing support for setting
75-
``nargs`` to ``+`` to indicate that at least one argument is required.
70+
This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.
7671

77-
This is supported by setting ``required=True``. However, this should
78-
not be used if you can avoid it as we believe scripts should gracefully
79-
degrade into becoming noops if a variadic argument is empty. The
80-
reason for this is that very often, scripts are invoked with wildcard
81-
inputs from the command line and they should not error out if the
82-
wildcard is empty.
72+
Argument Escape Sequences
73+
---------------------------
8374

84-
.. _file-args:
75+
If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.
8576

86-
File Arguments
87-
--------------
88-
89-
Since all the examples have already worked with filenames, it makes sense
90-
to explain how to deal with files properly. Command line tools are more
91-
fun if they work with files the Unix way, which is to accept ``-`` as a
92-
special file that refers to stdin/stdout.
93-
94-
Click supports this through the :class:`click.File` type which
95-
intelligently handles files for you. It also deals with Unicode and bytes
96-
correctly for all versions of Python so your script stays very portable.
97-
98-
Example:
77+
Example usage:
9978

10079
.. click:example::
10180
10281
@click.command()
103-
@click.argument('input', type=click.File('rb'))
104-
@click.argument('output', type=click.File('wb'))
105-
def inout(input, output):
106-
"""Copy contents of INPUT to OUTPUT."""
107-
while True:
108-
chunk = input.read(1024)
109-
if not chunk:
110-
break
111-
output.write(chunk)
112-
113-
And what it does:
114-
115-
.. click:run::
82+
@click.argument('files', nargs=-1, type=click.Path())
83+
def touch(files):
84+
"""Print all FILES file names."""
85+
for filename in files:
86+
click.echo(filename)
11687

117-
with isolated_filesystem():
118-
invoke(inout, args=['-', 'hello.txt'], input=['hello'],
119-
terminate_input=True)
120-
invoke(inout, args=['hello.txt', '-'])
88+
And from the command line:
12189

122-
File Path Arguments
123-
-------------------
90+
.. click:run::
12491
125-
In the previous example, the files were opened immediately. But what if
126-
we just want the filename? The naïve way is to use the default string
127-
argument type. The :class:`Path` type has several checks available which raise nice
128-
errors if they fail, such as existence. Filenames in these error messages are formatted
129-
with :func:`format_filename`, so any undecodable bytes will be printed nicely.
92+
invoke(touch, ['--', '-foo.txt', 'bar.txt'])
13093

131-
Example:
94+
If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:
13295

13396
.. click:example::
13497
135-
@click.command()
136-
@click.argument('filename', type=click.Path(exists=True))
137-
def touch(filename):
138-
"""Print FILENAME if the file exists."""
139-
click.echo(click.format_filename(filename))
98+
@click.command(context_settings={"ignore_unknown_options": True})
99+
@click.argument('files', nargs=-1, type=click.Path())
100+
def touch(files):
101+
"""Print all FILES file names."""
102+
for filename in files:
103+
click.echo(filename)
140104

141-
And what it does:
105+
And from the command line:
142106

143107
.. click:run::
144108
145-
with isolated_filesystem():
146-
with open('hello.txt', 'w') as f:
147-
f.write('Hello World!\n')
148-
invoke(touch, args=['hello.txt'])
149-
println()
150-
invoke(touch, args=['missing.txt'])
151-
152-
153-
File Opening Safety
154-
-------------------
155-
156-
The :class:`FileType` type has one problem it needs to deal with, and that
157-
is to decide when to open a file. The default behavior is to be
158-
"intelligent" about it. What this means is that it will open stdin/stdout
159-
and files opened for reading immediately. This will give the user direct
160-
feedback when a file cannot be opened, but it will only open files
161-
for writing the first time an IO operation is performed by automatically
162-
wrapping the file in a special wrapper.
163-
164-
This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to
165-
the constructor. If the file is opened lazily, it will fail its first IO
166-
operation by raising an :exc:`FileError`.
167-
168-
Since files opened for writing will typically immediately empty the file,
169-
the lazy mode should only be disabled if the developer is absolutely sure
170-
that this is intended behavior.
171-
172-
Forcing lazy mode is also very useful to avoid resource handling
173-
confusion. If a file is opened in lazy mode, it will receive a
174-
``close_intelligently`` method that can help figure out if the file
175-
needs closing or not. This is not needed for parameters, but is
176-
necessary for manually prompting with the :func:`prompt` function as you
177-
do not know if a stream like stdout was opened (which was already open
178-
before) or a real file that needs closing.
179-
180-
Starting with Click 2.0, it is also possible to open files in atomic mode by
181-
passing ``atomic=True``. In atomic mode, all writes go into a separate
182-
file in the same folder, and upon completion, the file will be moved over to
183-
the original location. This is useful if a file regularly read by other
184-
users is modified.
109+
invoke(touch, ['-foo.txt', 'bar.txt'])
185110

186111

187112
.. _environment-variables:
188113

189114
Environment Variables
190115
---------------------
191116

192-
Like options, arguments can also grab values from an environment variable.
193-
Unlike options, however, this is only supported for explicitly named
194-
environment variables.
117+
Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.
195118

196-
Example usage:
119+
Checking one environment variable:
197120

198121
.. click:example::
199122
@@ -208,59 +131,28 @@ And from the command line:
208131
.. click:run::
209132
210133
with isolated_filesystem():
134+
# Writing the file in the filesystem.
211135
with open('hello.txt', 'w') as f:
212136
f.write('Hello World!')
213137
invoke(echo, env={'SRC': 'hello.txt'})
214138

215-
In that case, it can also be a list of different environment variables
216-
where the first one is picked.
217-
218-
Generally, this feature is not recommended because it can cause the user
219-
a lot of confusion.
220-
221-
Option-Like Arguments
222-
---------------------
223139

224-
Sometimes, you want to process arguments that look like options. For
225-
instance, imagine you have a file named ``-foo.txt``. If you pass this as
226-
an argument in this manner, Click will treat it as an option.
227-
228-
To solve this, Click does what any POSIX style command line script does,
229-
and that is to accept the string ``--`` as a separator for options and
230-
arguments. After the ``--`` marker, all further parameters are accepted as
231-
arguments.
232-
233-
Example usage:
140+
Checking multiple environment variables:
234141

235142
.. click:example::
236143
237144
@click.command()
238-
@click.argument('files', nargs=-1, type=click.Path())
239-
def touch(files):
240-
"""Print all FILES file names."""
241-
for filename in files:
242-
click.echo(filename)
243-
244-
And from the command line:
245-
246-
.. click:run::
247-
248-
invoke(touch, ['--', '-foo.txt', 'bar.txt'])
249-
250-
If you don't like the ``--`` marker, you can set ignore_unknown_options to
251-
True to avoid checking unknown options:
252-
253-
.. click:example::
254-
255-
@click.command(context_settings={"ignore_unknown_options": True})
256-
@click.argument('files', nargs=-1, type=click.Path())
257-
def touch(files):
258-
"""Print all FILES file names."""
259-
for filename in files:
260-
click.echo(filename)
145+
@click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))
146+
def echo(src):
147+
"""Print value of SRC environment variable."""
148+
click.echo(src.read())
261149

262150
And from the command line:
263151

264152
.. click:run::
265153
266-
invoke(touch, ['-foo.txt', 'bar.txt'])
154+
with isolated_filesystem():
155+
# Writing the file in the filesystem.
156+
with open('hello.txt', 'w') as f:
157+
f.write('Hello World from second variable!')
158+
invoke(echo, env={'SRC_2': 'hello.txt'})

0 commit comments

Comments
 (0)