### Parser Setup for Tab Completion Example Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Sets up a basic ArgumentParser with an Optional[bool] argument for demonstrating tab completion behavior. ```python #!/usr/bin/env python3 from typing import Optional from jsonargparse import ArgumentParser parser = ArgumentParser() parser.add_argument("--bool", type=Optional[bool]) parser.parse_args() ``` -------------------------------- ### Add changelog entry example Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Example of how to format a changelog entry for a new release. If the section for unreleased changes does not exist, create it. ```text v4.28.0 (unreleased) -------------------- Added ^^^^^ - ``` -------------------------------- ### Install Latest Development Version Source: https://github.com/omni-us/jsonargparse/blob/main/README.rst Install the latest development version from the GitHub repository, including the 'signatures' extra. ```bash pip install "jsonargparse[signatures] @ https://github.com/omni-us/jsonargparse/zipball/main" ``` -------------------------------- ### Configuration File Example (YAML) Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Provides an example of a configuration file in YAML format, demonstrating how nested namespaces defined in jsonargparse correspond to the structure within the file. ```yaml cfg: optimizer: lr: 0.05 beta: 0.9 dataset: name: cifar10 ``` -------------------------------- ### Changelog Entry Example Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md An example of how to format a changelog entry for a new release, including version, date, and categorization of changes (e.g., Added, Changed, Fixed). ```default v4.28.0 (unreleased) -------------------- Added ^^^^^ - ``` -------------------------------- ### Example command-line execution with arguments Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Shows how to run a command-line tool with specific arguments, overriding default values and providing necessary inputs. ```bash $ python example.py Lucky --prize=1000 Lucky won 1000€! ``` -------------------------------- ### Creating an ArgumentParser Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Illustrates the basic setup of an ArgumentParser, similar to Python's built-in argparse, with options and their types. ```python from jsonargparse import ArgumentParser parser = ArgumentParser(prog="app", description="Description for my app.") parser.add_argument("--opt1", type=int, default=0, help="Help for option 1.") parser.add_argument("--opt2", type=float, default=1.0, help="Help for option 2.") ``` -------------------------------- ### Example command-line execution with settings class Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates running a command-line tool generated from a class that has no methods, resulting in an instance of the class being created with provided arguments. ```bash $ python example.py --name=Lucky Settings(name='Lucky', prize=100) ``` -------------------------------- ### Example command-line execution with help Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates how to view the help message for a command-line tool generated by jsonargparse, showing available arguments, their types, and descriptions. ```bash $ python example.py --help ... Prints the prize won by a person: name Name of winner. (required, type: str) --prize PRIZE Amount won. (type: int, default: 100) ``` -------------------------------- ### Install jsonargparse with Optional Extras Source: https://github.com/omni-us/jsonargparse/blob/main/README.rst Install jsonargparse with specific optional features enabled. Use 'all' to enable all optional features. ```bash pip install "jsonargparse[signatures,urls]" ``` ```bash pip install "jsonargparse[all]" ``` -------------------------------- ### Install Pre-commit Git Hooks Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Install pre-commit to automatically run unit tests and code checks locally before committing. ```bash pre-commit install ``` -------------------------------- ### Generate Completion Script from Command Line Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Example of generating a bash completion script and directing it to a system-wide directory. ```bash # example.py --print_completion=shtab-bash > /etc/bash_completion.d/example ``` -------------------------------- ### Install Development Requirements Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Install the necessary development and all optional requirements for jsonargparse using pip. ```bash pip install -e ".[dev,all]" ``` -------------------------------- ### Install all optional features of jsonargparse Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Install jsonargparse with all optional features enabled using the 'all' extra. Note that tab completion extras are excluded. ```bash pip install "jsonargparse[all]" # Enable all optional features ``` -------------------------------- ### Install jsonargparse Source: https://github.com/omni-us/jsonargparse/blob/main/README.rst Install the base jsonargparse package. PyYAML is installed by default. ```bash pip install jsonargparse ``` -------------------------------- ### Parse Arguments with Subcommands Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Provides examples of parsing command-line arguments with subcommands. Demonstrates how to select a subcommand and pass its arguments. ```python cfg = parser.parse_args(['--op0', 'val0', 'subcomm1', '--op1', 'val1']) print(cfg) # Namespace(op0='val0', subcomm1={'op1': 'val1'}) cfg = parser.parse_args(['subcomm2', '--op2', 'val2']) print(cfg) # Namespace(op0=None, subcomm2={'op2': 'val2'}) cfg = parser.parse_args(['--cfg', 'example.yaml']) print(cfg) # Namespace(op0='val0', subcomm1={'op1': 'val1'}) cfg = parser.parse_args(['--cfg', 'example.yaml'], defaults={'subcomm1': {'op1': 'default'}}) print(cfg) # Namespace(op0='val0', subcomm1={'op1': 'val1'}) ``` -------------------------------- ### Install jsonargparse with optional extras Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Install jsonargparse with specific optional features enabled using pip extras. For example, to enable signatures and URLs features. ```bash pip install "jsonargparse[signatures,urls]" # Enable signatures and URLs features ``` -------------------------------- ### Get Subclass Help via Command Line Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Shows how to request detailed help for a specific subclass by providing its import path to the help option. ```bash python tool.py --calendar.help calendar.TextCalendar ``` -------------------------------- ### Install jsonargparse tests package Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Install the separate tests package for jsonargparse, ensuring it matches the version of the main package. ```bash pip install jsonargparse_tests==4.47.0 ``` -------------------------------- ### Example command-line execution with class and method Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Illustrates running a method of a class via the command line when auto_cli() is used with a class, including passing arguments for both instantiation and the method. ```bash $ python example.py --max_prize=1000 person Lucky Lucky won 632€! ``` -------------------------------- ### Install and Run jsonargparse Tests Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Install the separate tests package for a specific version of jsonargparse and run the tests. This is recommended for versions v4.47.0 and later. ```bash pip install jsonargparse_tests==4.47.0 python -m jsonargparse_tests ``` -------------------------------- ### YAML Configuration for Unresolved Parameters Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Example of a YAML configuration file specifying class_path, init_args, and dict_kwargs for instantiation with unvalidated arguments. ```yaml class_path: MyClass init_args: foo: 1 dict_kwargs: bar: 2 ``` -------------------------------- ### Bash Command for Appending Classes Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Example of how to append multiple classes and set their arguments using the short notation on the command line. ```bash python tool.py \ --list_of_instances+={CLASS_1_PATH} \ --list_of_instances.{CLASS_1_ARG_1}=... \ --list_of_instances.{CLASS_1_ARG_2}=... \ --list_of_instances+={CLASS_2_PATH} \ --list_of_instances.{CLASS_2_ARG_1}=... \ ... \ --list_of_instances+={CLASS_N_PATH} \ --list_of_instances.{CLASS_N_ARG_1}=... \ ... ``` -------------------------------- ### YAML Configuration for Subcommands Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Shows a sample YAML configuration file that can be parsed by the jsonargparse subcommands example. The 'subcommand' key is not required in the config file. ```yaml # File: example.yaml op0: val0 subcomm1: op1: val1 ``` -------------------------------- ### Tab Completion Interaction Example Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates how tab completion provides guidance on expected types and available choices for an Optional[bool] argument. ```bash $ example.py --bool Expected type: Optional[bool]; 3/3 matched choices true false null $ example.py --bool f $ example.py --bool false ``` -------------------------------- ### YAML for Subclass Arguments Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Configuration example for using `add_subclass_arguments` where the `class_path` can be a different class than the type hint, and nested `init_args` are provided. ```yaml myclass: class_path: my_module.MyClass init_args: calendar: class_path: calendar.TextCalendar init_args: firstweekday: 1 ``` -------------------------------- ### Run jsonargparse tests Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Execute the jsonargparse tests using the installed tests package. ```bash python -m jsonargparse_tests ``` -------------------------------- ### Example command-line execution with nested subcommands Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Shows how to execute a function nested within subcommands defined by a dictionary structure in auto_cli(). ```bash $ python example.py weekend tier1 Lucky Lucky won 300€! ``` -------------------------------- ### OmegaConf Variable Interpolation Example Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates how OmegaConf can be used for variable interpolation in YAML files. This allows dynamic configuration values based on other defined variables. ```yaml server: host: localhost port: 80 client: url: http://${server.host}:${server.port}/ ``` -------------------------------- ### shtab completion behavior example Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates the completion behavior for boolean arguments and subclass types. It shows how shtab provides guidance on expected types, matched choices, and accepted parameters for subclasses. ```bash $ example.py --bool Expected type: Optional[bool]; 3/3 matched choices true false null ``` ```bash $ example.py --bool f $ example.py --bool false ``` ```bash $ example.py --cls Expected type: BaseClass; 3/3 matched choices some.module.BaseClass other.module.SubclassA other.module.SubclassB ``` ```bash $ example.py --cls other.module.SubclassA --cls. --cls.param1 --cls.param2 ``` ```bash $ example.py --cls other.module.SubclassA --cls.param2 Expected type: int; Accepted by subclasses: SubclassA ``` -------------------------------- ### Instantiate Model with Optimizer Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates how to add class arguments and instantiate a configuration, including nested optimizer settings. Ensure necessary classes are imported before parsing. ```default >>> parser.add_class_arguments(Model, 'model') >>> cfg = parser.get_defaults() >>> cfg.model.optimizer Namespace(class_path='__main__.SGD', init_args=Namespace(lr=0.05)) >>> init = parser.instantiate(cfg) >>> optimizer = init.model.optimizer([1, 2, 3]) >>> optimizer.params, optimizer.lr ([1, 2, 3], 0.05) ``` -------------------------------- ### Clone Repository and Set Up Development Environment Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Steps to clone the jsonargparse repository, create a virtual environment, and activate it. ```bash git clone https://github.com/omni-us/jsonargparse.git cd jsonargparse python -m venv venv . venv/bin/activate ``` -------------------------------- ### Specify Subclass and Init Args via Command Line Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Illustrates specifying a subclass and its initialization arguments using multiple command-line arguments, including nested init args. ```bash python tool.py \ --calendar.class_path calendar.TextCalendar \ --calendar.init_args.firstweekday 1 ``` -------------------------------- ### Parse Configuration from String Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates parsing a configuration directly from a string. This is useful when the configuration is not stored in a file. ```python cfg = parser.parse_args(["--config", '{"lev1":{"opt1":"from string 1"}}']) print(cfg.lev1.opt1) ``` -------------------------------- ### Test Completion Script Interactively Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Evaluate a completion script directly in the shell to test its behavior without installation. ```bash $ eval "$(example.py --print_completion=shtab-bash)" ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Command to build the project documentation using Sphinx. ```bash sphinx-build sphinx sphinx/_build sphinx/*.rst ``` -------------------------------- ### Instantiate Optimizer with Protocol Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates using a Protocol to define an optimizer factory and parsing it with jsonargparse. This allows for keyword arguments during instantiation. ```python class OptimizerFactory(Protocol): def __call__(self, params: Iterable) -> Optimizer: ... parser = ArgumentParser() value = { "class_path": "SGD", "init_args": { "lr": 0.02, }, } parser.add_argument("--optimizer", type=OptimizerFactory) # doctest: +IGNORE_RESULT cfg = parser.parse_args(["--optimizer", str(value)]) init = parser.instantiate(cfg) optimizer = init.optimizer(params=[6, 5]) ``` -------------------------------- ### instantiate Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Instantiates all signature components in a configuration namespace. It recursively processes the configuration, converting registered signature components into their corresponding Python objects. ```APIDOC ## instantiate(cfg: [Namespace](#jsonargparse.Namespace), instantiate_groups: bool = True) -> [Namespace](#jsonargparse.Namespace) ### Description Instantiates all signature components in a configuration namespace. Processes the configuration recursively, converting each signature component registered with the parser into its corresponding Python object. ### Parameters * **cfg** – The configuration object to use. Must have been produced by one of the `parse_*` methods and not modified in a way that breaks the structure expected by the parser. * **instantiate_groups** – Whether class groups should be instantiated. ### Returns A new configuration object where every registered signature component has been replaced by its corresponding Python object. ``` -------------------------------- ### Specify Init Args with Implicit Class Path Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Shows how to provide initialization arguments directly, implicitly using the base class as the class path when the base class is not abstract. ```bash python tool.py --calendar.firstweekday 2 ``` -------------------------------- ### parser_mode Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Mode for parsing config files. This property can be read to get the current mode, and written to set a new mode. ```APIDOC ## *property* parser_mode *: str* ### Description Mode for parsing config files, `yaml`, `json`, `jsonnet` or ones added via [`set_loader()`](#jsonargparse.set_loader). ### Getter Returns the current parser mode. ### Setter Sets the parser mode. ### Raises **ValueError** – If an invalid value is given. ``` -------------------------------- ### env_prefix Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md The environment variables prefix property. This property can be read to get the current prefix, and written to set a new prefix. ```APIDOC ## *property* env_prefix *: bool | str* ### Description The environment variables prefix property. ### Getter Returns the current environment variables prefix. ### Setter Sets the environment variables prefix. ### Raises **ValueError** – If an invalid value is given. ``` -------------------------------- ### Get Parser from auto_cli Function Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates the convenience function auto_parser() which internally uses capture_parser() to retrieve a parser instance. ```python from jsonargparse import auto_parser # Assuming auto_cli is defined elsewhere and returns a parser # parser = auto_parser() # print(parser.help()) ``` -------------------------------- ### Instantiate Configuration Object Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Use the instantiate method to create instances of classes defined in the configuration object. This simplifies the process of initializing objects from parsed arguments. ```python cfg = parser.instantiate(cfg) ``` -------------------------------- ### FromConfigMixin for Direct Instantiation Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Utilize FromConfigMixin to add a class method 'from_config' for direct instantiation from dictionaries or configuration files. This is useful for small utilities. ```python from jsonargparse import FromConfigMixin class Client(FromConfigMixin): def __init__(self, host: str = "localhost", port: int = 80): self.host = host self.port = port client = Client.from_config({"host": "api.local", "port": 8080}) (client.host, client.port) ``` -------------------------------- ### Running with a configuration file Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Tools created with auto_cli() support the --config option to load settings from a configuration file. This is especially useful when dealing with numerous configurable parameters. ```bash python example.py --config config.yaml ``` -------------------------------- ### Basic CLI with auto_cli Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates a simple use case of auto_cli for command-line interface generation with string arguments. ```python >>> auto_cli(components, args=["weekend", "tier1", "Lucky"]) 'Lucky won 300€!' ``` -------------------------------- ### Register Complex Type Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Example of registering a built-in type like `complex` with `jsonargparse.typing.register_type`. This allows the type to be used directly in type hints. ```python from jsonargparse.typing import register_type register_type(complex) # Equivalent to: register_type(complex, serializer=str, deserializer=complex) ``` -------------------------------- ### Printing Default Configuration Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Shows how to print the default configuration of a script to a file, which can then be modified. ```bash # Dump default config to have as reference python example.py --print_config > config.yaml # Modify the config as needed (all default settings can be removed) nano config.yaml # Run the tool using the adapted config python example.py --config config.yaml ``` -------------------------------- ### Instantiate SGD with Callable Type Hint Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates parsing arguments for a Callable type hint that returns an Optimizer, and then instantiating the callable to create an SGD optimizer instance. ```python value = { "class_path": "SGD", "init_args": { "lr": 0.01, }, } parser.add_argument("--optimizer", type=Callable[[Iterable], Optimizer]) # doctest: +IGNORE_RESULT cfg = parser.parse_args(["--optimizer", str(value)]) cfg.optimizer init = parser.instantiate(cfg) optimizer = init.optimizer([1, 2, 3]) isinstance(optimizer, SGD) optimizer.params, optimizer.lr ``` -------------------------------- ### dump_header Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Header to include as comment when dumping a config object. This property can be read to get the current header, and written to set a new header. ```APIDOC ## *property* dump_header *: list[str] | None* ### Description Header to include as comment when dumping a config object. ### Getter Returns the current dump header. ### Setter Sets the dump header. ### Raises **ValueError** – If an invalid value is given. ``` -------------------------------- ### default_env Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Whether by default environment variables parsing is enabled. This property can be read to get the current default setting, and written to set a new default. ```APIDOC ## *property* default_env *: bool* ### Description Whether by default environment variables parsing is enabled. ### Getter Returns the current default environment variables parsing setting. ### Setter Sets the default environment variables parsing setting. ### Raises **ValueError** – If an invalid value is given. ``` -------------------------------- ### Instantiate Class from YAML Config Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Use a YAML configuration file to specify a class path and initialization arguments for instantiation. The 'class_path' points to the class, and 'init_args' provides its constructor parameters. ```yaml myclass: calendar: class_path: calendar.Calendar init_args: firstweekday: 1 ``` -------------------------------- ### JSON Schema Validation with jsonargparse Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Example of adding an argument that uses ActionJsonSchema for parsing and validating input against a provided JSON schema. Requires the 'jsonschema' package. ```python from jsonargparse import ActionJsonSchema parser = ArgumentParser() parser.add_argument("--json", action=ActionJsonSchema(schema=schema)) ``` ```python parser.parse_args(["--json", '{"price": 1.5, "name": "cookie"}']) ``` -------------------------------- ### Create and Parse Arguments with ArgumentParser Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Demonstrates the basic usage of ArgumentParser, similar to Python's argparse, for defining and parsing command-line arguments. ```python from jsonargparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-f', '--foo') cfg = parser.parse_args(['--foo', 'bar']) print(cfg.foo) ``` -------------------------------- ### Using Config Argument for Explicit Configuration File Loading Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Shows how to add an argument to explicitly provide a config file path. This argument can be used multiple times, with later instances overriding earlier ones. ```python >>> from jsonargparse import ArgumentParser >>> parser = ArgumentParser() >>> parser.add_argument("--lev1.opt1", default="from default 1") # doctest: +IGNORE_RESULT >>> parser.add_argument("--lev1.opt2", default="from default 2") # doctest: +IGNORE_RESULT >>> parser.add_argument("--config", action="config") # doctest: +IGNORE_RESULT >>> cfg = parser.parse_args(["--lev1.opt1", "from arg 1", "--config", "example.yaml", "--lev1.opt2", "from arg 2"]) >>> cfg.lev1.opt1 'from yaml 1' >>> cfg.lev1.opt2 'from arg 2' ``` -------------------------------- ### Exclude arguments when adding method arguments Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Use the `skip` parameter in `add_method_arguments` to exclude specific arguments from being added to the parser, for example, internal or optional arguments that should not be configured. ```python parser.add_method_arguments(MyClass, 'mymethod', skip={'flag'}) ``` -------------------------------- ### Configuration File Structure Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Define configuration settings for class instantiation and method calls in separate YAML files. This allows for modular configuration management. ```yaml myclass: init: myclass.yaml method: mymethod.yaml ``` -------------------------------- ### Define a user-defined type for arguments Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst User-defined types for arguments must be idempotent. This example shows a function that accepts either an integer greater than zero or the string 'off'. ```python # either int larger than zero or 'off' string def int_or_off(x): return x if x == "off" else int(x) parser.add_argument("--int_or_off", type=int_or_off) ``` -------------------------------- ### Specify Default Configuration Files Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Explains how to set default configuration files for an ArgumentParser using the `default_config_files` attribute. The parser will search for and apply these files in the specified order, overriding defaults. ```python from jsonargparse import ArgumentParser parser = ArgumentParser( default_config_files=['~/.myapp.yaml', '/etc/myapp.yaml'] ) # If ~/.myapp.yaml exists and contains: # cfg: # optimizer: # lr: 0.02 # Then cfg.cfg.optimizer.lr will be 0.02 unless overridden by command line arguments. ``` -------------------------------- ### Parse Complex-Valued Points Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Illustrates parsing complex-valued points using jsonargparse, where the type hint is a generic class. This example shows how to provide initialization arguments for the generic type. ```python from jsonargparse.typing import Complex parser.parse_args(['--point', '1+2j', '--point.real', '3', '--point.imag', '4j']) # Point(real=3, imag=4j) ``` -------------------------------- ### Parsing Configuration Files with jsonargparse Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates how to parse configuration files (YAML by default) to override argument defaults. The dot notation hierarchy defines the expected structure. ```yaml # File: example.yaml lev1: opt1: from yaml 1 opt2: from yaml 2 ``` -------------------------------- ### default_config_files Source: https://github.com/omni-us/jsonargparse/blob/main/sphinx/index.md Default config file locations. This property can be read to get the current default config file locations, and written to set new default config file locations. ```APIDOC ## *property* default_config_files *: list[str]* ### Description Default config file locations. ### Getter Returns the current default config file locations. ### Setter Sets new default config file locations, e.g. `['~/.config/myapp/*.yaml']`. ### Raises **ValueError** – If an invalid value is given. ``` -------------------------------- ### Specify Subclass by Name Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates a more concise way to specify a subclass by its name instead of the full import path, provided the module has been imported. It also shows how to directly provide init_args when the base class is not abstract. ```bash python tool.py --calendar TextCalendar --calendar.firstweekday 1 ``` ```bash python tool.py --calendar.firstweekday 2 ``` -------------------------------- ### Implement Always Fail Argument Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Use the ActionFail action to include an argument in the parser that will always fail parsing. This is useful for features that depend on external conditions, like installed packages. ```python from jsonargparse import ActionFail if some_package_installed: parser.add_argument("--module", type=SomeClass) else: parser.add_argument( "--module", action=ActionFail(message="install 'package' to enable %(option)s"), help="Option unavailable due to missing 'package'", ) ``` -------------------------------- ### Using ActionYesNo for Paired Boolean Options Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates the use of ActionYesNo to create paired options for setting boolean arguments to True or False, e.g., --opt1 and --no_opt1. ```python from jsonargparse import ActionYesNo, ArgumentParser parser = ArgumentParser() # --opt1 for true and --no_opt1 for false. ``` -------------------------------- ### Default Callable Instance Factory with Lambda Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Example of setting a default value for a parameter typed as a Callable instance factory using a lambda function, which provides default initialization arguments. ```python class Model: def __init__( self, optimizer: Callable[[Iterable], Optimizer] = lambda p: SGD(p, lr=0.05), ): self.optimizer = optimizer parser.add_class_arguments(Model, 'model') cfg = parser.get_defaults() cfg.model.optimizer init = parser.instantiate(cfg) ``` -------------------------------- ### Use Type Hints for Validation Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Leverage Python's type hinting system with jsonargparse for advanced argument validation. This example shows optional, union, and custom interval types. ```python from typing import Optional, Union from jsonargparse.typing import PositiveInt, OpenUnitInterval parser.add_argument("--op", type=Optional[Union[PositiveInt, OpenUnitInterval]]) ``` -------------------------------- ### Dump Configuration for Final Class Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Demonstrates the output of dumping a configuration for a class decorated with @final, showing that instantiation arguments are stored directly. ```python >>> print(parser.dump(cfg)) # doctest: +NORMALIZE_WHITESPACE data: number: 8 accepted: true ``` -------------------------------- ### Generate full test coverage report with tox Source: https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst Clean previous coverage data, run tox with coverage for all supported Python versions, and generate a full HTML coverage report. This requires all supported Python versions to be installed. ```bash rm -fr jsonargparse_tests/.coverage jsonargparse_tests/htmlcov tox -- --cov=../jsonargparse --cov-append cd jsonargparse_tests coverage html ``` -------------------------------- ### Python Code for Class Instantiation from Config Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Python code demonstrating how to parse a YAML configuration file and instantiate a class with injected dependencies. Requires importing ArgumentParser and the target class. ```python from calendar import Calendar class MyClass: def __init__(self, calendar: Calendar): self.calendar = calendar parser = ArgumentParser() parser.add_class_arguments(MyClass, "myclass") # doctest: +IGNORE_RESULT cfg = parser.parse_path("config.yaml") cfg.myclass.calendar.as_dict() cfg = parser.instantiate(cfg) isinstance(cfg.myclass, MyClass) isinstance(cfg.myclass.calendar, Calendar) cfg.myclass.calendar.getfirstweekday() ``` -------------------------------- ### Class Instance Defaults with Constant Values Source: https://github.com/omni-us/jsonargparse/blob/main/DOCUMENTATION.rst Shows how class instances can be defined with keyword arguments that have constant values, or created via lambdas that also use constant values. This is relevant for static analysis of default configurations. ```python # Class instance: only keyword arguments with ``ast.Constant`` value class_instance: SomeClass = SomeClass(param=1) # Lambda returning class instance: only keyword arguments with ``ast.Constant`` value class_instance: Callable[[type], BaseClass] = lambda a: ChildClass(a, param=2.3) ```