Skip to content
Myr

Apply suggestions from code review for arguments docs.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Edward G · committed by Edward G · parent e9a76ba · Browse files · 2 files+29 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+29 added−25 removed

  • other:+29 added−25 removed

2 files+29 added−25 removed

modified:docs/arguments.rst+16 added-16 removed
5 unmodified lines
6.. currentmodule:: click78Arguments are:910* Are positional in nature10* Are positional in nature.11* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12* :ref:`documented manually <documenting-arguments>`12* :ref:`Documented manually <documenting-arguments>`.1314Useful and often used kwargs are:1516* ``default`` : Passes a default17* ``nargs`` : Sets the number of arguments. Set to -1 to take an arbitrary number.16* ``default``: Passes a default.17* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.1819Basic Argument19Basic Arguments20---------------2122A minimal :class:`click.Argument` takes the name of function argument. If you just pass it this, it assumes 1 argument, required, no default and string type.22A 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``.2324Example:2526.. click:example::2728 @click.command()29 @click.argument('filename')30 def touch(filename):30 def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)3334And what it looks like:34And from the command line:3536.. click:run::3738 invoke(touch, args=['foo.txt'])394041An 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 STRING.41An 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`.4243.. admonition:: Note on Required Arguments4445 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.
7 unmodified lines
5354 @click.command()55 @click.argument('src', nargs=1)56 @click.argument('dsts', nargs=-1)57 def copy(src, dsts):57 def copy(src: str, dsts: tuple[str, ...]):58 """Move file SRC to DST."""59 for destination in dsts:60 click.echo(f"Copy {src} to folder {destination}")6162And what it looks like:62And from the command line:6364.. click:run::6566 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])6768.. admonition:: Note on Handling Files.68.. admonition:: Note on Handling Files6970 This is not how you would handle files and files paths, since it passes them in as strings. For more see :ref:`handling-files`.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.7172Argument Escape Sequences73---------------------------74
3 unmodified lines
7879.. click:example::8081 @click.command()82 @click.argument('files', nargs=-1, type=click.Path())83 def touch(files):82 @click.argument('files', nargs=-1, type=click.Path(path_type=pathlib.Path))83 def touch(files: tuple[pathlib.Path, ...]):84 """Print all FILES file names."""85 for filename in files:86 click.echo(filename)87
25 unmodified lines
113114Environment Variables115---------------------116117Arguments can use environment variables. To do so pass the name of the environment variable(s) into ``click.argument``.117Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118119Checking one environment variable:120121.. click:example::
37 unmodified lines
modified:docs/handling-files.rst+13 added-9 removed
3 unmodified lines
4================56.. currentmodule:: click78Click has built in features to support file and file path handling. Since files and files paths are recommended to be passed in as arguments, the examples use arguments.8Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.910.. _file-args:1112File Arguments13-----------------1415Click supports working with files with the :class:`File` type. Some notable features are:1617* Support for ``-`` to mean a special file that refers to stdin/stdout. This is common pattern for POSIX command line utilities, for example wget.18* Deals with Unicode and bytes correctly for all versions of Python.17* Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities.18* Deals with ``str`` and ``bytes`` correctly for all versions of Python.1920Example:2122.. click:example::
8 unmodified lines
31 if not chunk:32 break33 output.write(chunk)3435And what it does:35And from the command line:3637.. click:run::3839 with isolated_filesystem():
3 unmodified lines
4344File Path Arguments45----------------------4647For handling paths, the :class:`Path` type is better than a string. Some notable features are:47For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:4849* It can run checks such as does the path exist or is the file executable.50* It also handles formatting error messages with :func:`format_filename` so any undecodable bytes will be printed nicely.49* The ``exists`` argument will verify whether the path exists.50* ``readable``, ``writable``, and ``executable`` can perform permission checks.51* ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted.52* Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely.5354See :class:`Path` for all features.5556Example:5758.. click:example::59
2 unmodified lines
62 def touch(filename):63 """Print FILENAME if the file exists."""64 click.echo(click.format_filename(filename))6562And what it does:66And from the command line:6768.. click:run::6970 with isolated_filesystem():
11 unmodified lines
8283File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:8485* A failure at first IO operation will happen by raising an :exc:`FileError`.82* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will receive a ``close_intelligently`` method that can help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).86* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).8788Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.8990It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.