Skip to content

Commit de69d75

Browse files
authored
Documentation fixes and improvements (#806)
1 parent e2e4ff4 commit de69d75

File tree

2 files changed

+45
-32
lines changed

2 files changed

+45
-32
lines changed

DOCUMENTATION.rst

Lines changed: 44 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ A wide range of type hints are supported and with arbitrary complexity/nesting.
453453
Some notes about this support are:
454454

455455
- Nested types are supported as long as at least one child type is supported. By
456-
nesting it is meant child types inside ``List``, ``Dict``, etc. There is no
456+
nesting it is meant child types inside ``list``, ``dict``, etc. There is no
457457
limit in nesting depth.
458458

459459
- Postponed evaluation of types PEP `563 <https://peps.python.org/pep-0563/>`__
@@ -468,25 +468,25 @@ Some notes about this support are:
468468

469469
- Fully supported types are: ``str``, ``bool`` (more details in
470470
:ref:`boolean-arguments`), ``int``, ``float``, ``Decimal``, ``complex``,
471-
``bytes``/``bytearray`` (Base64 encoding), ``range``, ``List`` (more details
471+
``bytes``/``bytearray`` (Base64 encoding), ``range``, ``list`` (more details
472472
in :ref:`list-append`), ``Iterable``, ``Sequence``, ``Any``, ``Union``,
473473
``Optional``, ``Type``, ``Enum``, ``PathLike``, ``UUID``, ``timedelta``,
474474
restricted types as explained in sections :ref:`restricted-numbers` and
475475
:ref:`restricted-strings` and paths and URLs as explained in sections
476476
:ref:`parsing-paths` and :ref:`parsing-urls`.
477477

478-
- ``Dict``, ``Mapping``, ``MutableMapping``, ``MappingProxyType``,
478+
- ``dict``, ``Mapping``, ``MutableMapping``, ``MappingProxyType``,
479479
``OrderedDict``, and ``TypedDict`` are supported but only with ``str`` or
480480
``int`` keys. ``Required`` and ``NotRequired`` are also supported for
481481
fine-grained specification of required/optional ``TypedDict`` keys.
482482
``Unpack`` is supported with ``TypedDict`` for more precise ``**kwargs``
483483
typing as described in PEP `692 <https://peps.python.org/pep-0692/>`__.
484484
For more details see :ref:`dict-items`.
485485

486-
- ``Tuple``, ``Set`` and ``MutableSet`` are supported even though they can't be
487-
represented in JSON distinguishable from a list. Each ``Tuple`` element
488-
position can have its own type and will be validated as such. ``Tuple`` with
489-
ellipsis (``Tuple[type, ...]``) is also supported. In command line arguments,
486+
- ``tuple``, ``set`` and ``MutableSet`` are supported even though they can't be
487+
represented in JSON distinguishable from a list. Each ``tuple`` element
488+
position can have its own type and will be validated as such. ``tuple`` with
489+
ellipsis (``tuple[type, ...]``) is also supported. In command line arguments,
490490
config files and environment variables, tuples and sets are represented as an
491491
array.
492492

@@ -664,16 +664,15 @@ actual path, thus for the previous example:
664664
>>> os.fspath(cfg.databases.info) # doctest: +ELLIPSIS
665665
'/.../app/data/info.db'
666666

667-
The content of a file that a :class:`.Path` instance references can be read by
668-
using the :py:meth:`.Path.get_content` method. For the previous example would be
667+
The content of a file referenced by a :class:`.Path` instance can be read using
668+
the :py:meth:`.Path.get_content` method. For the previous example, this would be
669669
``info_db = cfg.databases.info.get_content()``.
670670

671671
An argument with a path type can be given ``nargs='+'`` to parse multiple paths.
672-
The CLI syntax for a list of paths is ``[/path/a,/path/b]`` for the default yaml
673-
loader and ``["/path/a","/path/b"]`` for the json loader.
674-
But it might also be wanted to parse a list of paths found in a plain text file
675-
or from stdin. For this add the argument with type ``List[<path_type>]`` and
676-
``enable_path=True``. To read from stdin give the special string ``'-'``.
672+
Thus, from command line you could do ``--files file1 file2``, separated by
673+
space. It might also be desired to parse a list of paths found in a plain text
674+
file or from stdin. For this add the argument with type ``list[<path_type>]``
675+
and ``enable_path=True``. To read from stdin give the special string ``'-'``.
677676
Example:
678677

679678
.. testsetup:: path_list
@@ -682,6 +681,8 @@ Example:
682681
tmpdir = tempfile.mkdtemp(prefix="_jsonargparse_doctest_")
683682
os.chdir(tmpdir)
684683
pathlib.Path("paths.lst").write_text("paths.lst\n")
684+
pathlib.Path("file1").touch()
685+
pathlib.Path("file2").touch()
685686

686687
parser = ArgumentParser()
687688

@@ -698,16 +699,29 @@ Example:
698699

699700
from jsonargparse.typing import Path_fr
700701

701-
parser.add_argument("--list", type=List[Path_fr], enable_path=True)
702+
parser.add_argument("--list", type=list[Path_fr], enable_path=True)
702703
cfg = parser.parse_args(["--list", "paths.lst"]) # File with list of paths
703704
cfg = parser.parse_args(["--list", "-"]) # List of paths from stdin
704705

705-
If ``nargs='+'`` is given to ``add_argument`` with ``List[<path_type>]`` and
706-
``enable_path=True`` then for each argument a list of paths is generated.
706+
In this case since there is no ``nargs``, the argument expects a single value.
707+
That is why to provide multiple paths directly from command line, a more
708+
cumbersome YAML/JSON array syntax is required, i.e. ``--list "[file1,file2]".
709+
However, the simpler syntax described in :ref:`list-append` can also be used,
710+
which would be like ``--list+ file1 --list+ file2``. Not as simple as with
711+
``nargs='+'`` but with tab completion enabled the effort is minimal.
707712

708-
Path list arguments can also be specified using the
709-
:py:meth:`.ArgumentParser.add_class_arguments` method. To do so, specify
710-
``List[<path_type>]`` as your class member's type.
713+
The same ``list[<path_type>]`` behavior described here will work for arguments
714+
automatically created from type hints in signatures, that is with
715+
:func:`.auto_cli`, :py:meth:`.ArgumentParser.add_function_arguments`,
716+
:py:meth:`.ArgumentParser.add_class_arguments`,
717+
:py:meth:`.ArgumentParser.add_method_arguments` and
718+
:py:meth:`.ArgumentParser.add_subclass_arguments`.
719+
720+
.. note::
721+
722+
If ``nargs='+'`` and ``enable_path=True`` are set for an argument of type
723+
``list[<path_type>]``, each argument will produce a list of paths. This
724+
behavior may not be what you expect.
711725

712726
.. note::
713727

@@ -838,7 +852,7 @@ desired values. For example:
838852
List append
839853
-----------
840854

841-
As detailed before, arguments with ``List`` type are supported. By default when
855+
As detailed before, arguments with ``list`` type are supported. By default when
842856
specifying an argument value, the previous value is replaced, and this also
843857
holds for lists. Thus, a parse such as ``parser.parse_args(['--list=[1]',
844858
'--list=[2, 3]'])`` would result in a final value of ``[2, 3]``. However, in
@@ -855,7 +869,7 @@ can be achieved by adding ``+`` as suffix to the argument key, for example:
855869

856870
.. doctest:: append
857871

858-
>>> parser.add_argument("--list", type=List[int]) # doctest: +IGNORE_RESULT
872+
>>> parser.add_argument("--list", type=list[int]) # doctest: +IGNORE_RESULT
859873
>>> parser.parse_args(["--list=[1]", "--list+=[2, 3]"])
860874
Namespace(list=[1, 2, 3])
861875
>>> parser.parse_args(["--list=[4]", "--list+=5"])
@@ -886,7 +900,7 @@ added to a parser as:
886900

887901
.. testcode:: append
888902

889-
parser.add_argument("--list_of_instances", type=List[MyBaseClass])
903+
parser.add_argument("--list_of_instances", type=list[MyBaseClass])
890904

891905
Thanks to the short notation, command line arguments don't require to specify
892906
``class_path`` and ``init_args``. Thus, multiple classes can be appended and its
@@ -916,7 +930,7 @@ intuitive to write and understand.
916930
Dict items
917931
----------
918932

919-
When an argument has ``Dict`` as type, the value can be set using JSON format,
933+
When an argument has ``dict`` as type, the value can be set using JSON format,
920934
e.g.:
921935

922936
.. testsetup:: dict_items
@@ -1414,11 +1428,11 @@ Take for example a class with its init and a method with docstrings as follows:
14141428

14151429
.. testcode:: class_method
14161430

1417-
from typing import Dict, Union, List
1431+
from typing import Union
14181432

14191433

14201434
class MyClass(MyBaseClass):
1421-
def __init__(self, foo: Dict[str, Union[int, List[int]]], **kwargs):
1435+
def __init__(self, foo: dict[str, Union[int, list[int]]], **kwargs):
14221436
"""Initializer for MyClass.
14231437
14241438
Args:
@@ -1887,11 +1901,10 @@ jsonargparse with the ``signatures`` extra as explained in section
18871901
:ref:`installation`.
18881902

18891903
Many of the types defined in stub files use the latest syntax for type hints,
1890-
that is, bitwise or operator ``|`` for unions and generics, e.g.
1891-
``list[<type>]`` instead of ``typing.List[<type>]``, see PEP `604
1904+
that is, bitwise or operator ``|`` for unions, see PEP `604
18921905
<https://peps.python.org/pep-0604>`__. On ``python>=3.10`` these are fully
1893-
supported. On ``python<=3.9`` backporting these types is attempted and in some cases
1894-
it can fail. On failure the type annotation is set to ``Any``.
1906+
supported. On ``python<=3.9`` backporting these types is attempted and in some
1907+
cases it can fail. On failure the type annotation is set to ``Any``.
18951908

18961909
Most of the types in the Python standard library have their types in stubs. An
18971910
example from the standard library would be:
@@ -2357,7 +2370,7 @@ An example of a target being in a subclass is:
23572370
def __init__(
23582371
self,
23592372
save_dir: Optional[str] = None,
2360-
logger: Union[bool, Logger, List[Logger]] = False,
2373+
logger: Union[bool, Logger, list[Logger]] = False,
23612374
):
23622375
self.logger = logger
23632376

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
66
[project]
77
name = "jsonargparse"
88
dynamic = ["version"]
9-
description = "Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables."
9+
description = "Minimal effort CLIs derived from type hints and parse from command line, config files and environment variables."
1010
authors = [
1111
{name = "Mauricio Villegas", email = "mauricio@omnius.com"},
1212
]

0 commit comments

Comments
 (0)