Registry / serialization / configargparse

configargparse

JSON →
library1.7.5pypypi✓ verified 26d ago

ConfigArgParse is a drop-in replacement for Python's standard `argparse` module, enhancing it with the ability to load configuration options from command-line arguments, environment variables, and configuration files (INI, YAML, TOML formats). It offers a unified API to define, document, and parse settings from multiple sources with a clear precedence order (command line > environment variables > config file values > defaults). The library is actively maintained, with its current version being 1.7.5.

pip install configargparse
INSTALL
IMPORT
SIG · CONFIGARGPARSE
C
configargparse
serializationpythonv1.7.5
Install
1.6s avg
Import
29ms
Disk
18MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.7.5 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 0.031s · 20.1MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 1.6s · import 0.028s · 21MB
18MB installed
● package 18MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ArgumentParser
from configargparse import ArgumentParser
import configargparse.ArgumentParser
While `configargparse` is the module, its primary class `ArgumentParser` is typically imported directly. The alias `ArgParser` is also available.

This quickstart demonstrates how to define arguments and have them automatically loaded from a default config file and environment variables, with command-line arguments taking the highest precedence. It sets up a basic `ArgumentParser`, defines a config file and an environment variable, then parses the arguments to show the effective values based on precedence. It also shows how to add an argument to specify an alternative config file.

import configargparse import os # Simulate an environment variable os.environ['MYAPP_HOST'] = 'localhost' # Create a dummy config file config_content = """ host = 127.0.0.1 port = 8080 debug = false """ with open('my_config.ini', 'w') as f: f.write(config_content) # Initialize the parser p = configargparse.ArgumentParser( default_config_files=['./my_config.ini'], auto_env_var_prefix='MYAPP_' ) # Add arguments p.add('--host', help='Host address') p.add('--port', type=int, help='Port number') p.add('--debug', action='store_true', help='Enable debug mode') p.add('-c', '--config', is_config_file_arg=True, help='Path to config file') # Parse arguments (simulate command line: --port 9000) # `parse_args` can take a list of args, e.g., ['--port', '9000'] # For this example, we'll let it parse from system args (or defaults/env/config) # If running as a script, try: python your_script.py --port 9000 # You can also set MYAPP_PORT=9001 in your shell before running. # For the demo, let's explicitly provide some command-line args. args = p.parse_args(['--port', '9002']) print(f"Host: {args.host} (from config file, overridden by env var if present) ") print(f"Port: {args.port} (command line > env var > config > default)") print(f"Debug: {args.debug} (from config file)") # Cleanup (optional) os.remove('my_config.ini') del os.environ['MYAPP_HOST'] # Clean up the simulated env var # Expected precedence: command line > environment variables > config file values > defaults # In this example: # - Host: 'localhost' (from MYAPP_HOST env var, overrides 127.0.0.1 in config) # - Port: 9002 (from explicit command line, overrides 8080 and any MYAPP_PORT) # - Debug: False (from config file 'debug=false' which becomes --debug false; action='store_true' needs --debug to be present for True) # Actually, `debug = false` in INI for `action='store_true'` will effectively NOT set the flag, resulting in False. If you want true, it should be `debug=true` or just `debug`. # Let's verify debug: `debug = false` in INI would mean the flag `--debug` is NOT present, so `args.debug` defaults to `False` for `action='store_true'`. If `debug=true` it would be `True`.
Debug
Known issues
breakingPrior to v1.7.4, environment variables were ignored when used in conjunction with subparsers. This could lead to unexpected behavior where subcommands would not receive their intended environment-sourced configuration.
fix
Upgrade to v1.7.4 or later. For older versions, explicitly pass environment variable values as command-line arguments to the subparser, or ensure critical arguments are defined directly on subparsers with `env_var` if not relying on `auto_env_var_prefix`.
affects: <1.7.4
breakingIn versions prior to v1.7.3/v1.7.4, using `nargs=argparse.REMAINDER` or the `--` separator could lead to config file options being 'swallowed' or incorrectly parsed. This resulted in config file settings not being applied or arguments being misinterpreted as positional arguments.
fix
Upgrade to v1.7.3 or later. These versions contain fixes for proper handling of `nargs=REMAINDER` and the `--` separator, ensuring config file arguments are inserted correctly into the argument list.
affects: <1.7.3
gotchaConfigArgParse introduced stricter input validation for `ArgumentParser.__init__()` in v1.7.4. Passing incorrect types for parameters like `config_file_parser_class`, `formatter_class`, `default_config_files`, `args_for_setting_config_path`, or `args_for_writing_out_config_file` will now raise a `TypeError` with a clear message.
fix
Ensure that arguments passed to the `ArgumentParser` constructor adhere to the expected types (e.g., `config_file_parser_class` must be a subclass of `ConfigFileParser`, lists/tuples for file path arguments). Refer to the documentation for correct parameter types.
affects: >=1.7.4
gotchaWhen defining boolean flags with `action='store_true'` or `action='store_false'`, set them as `key = true` or `key = false` in config files or environment variables. For arguments with `action='append'` (lists), use `key = [value1, value2]` or multiple `key = value` lines (depending on parser). A simple `key = value` will be treated as `--key value`.
fix
Understand the 'Special Values' handling. For boolean flags (`action='store_true'`), `key=true` is interpreted as `"--key"` (setting it to True). `key=false` or omitting the key will result in `False`. For lists, `key = [item1, item2]` is generally supported by modern parsers (e.g., `TomlConfigParser`), or ensure your parser handles multiple lines if you intend to append.
affects: All versions
gotchaOnly command-line arguments that have a long version (i.e., start with `--`, e.g., `--my-option`) can be set via config files. Short arguments (e.g., `-m`) cannot directly be specified in config files.
fix
Always define a long argument (`--my-option`) if you intend for an option to be configurable via a config file. The corresponding config file key can then be `my-option` or `--my-option`.
affects: All versions
gotchaPrior to v1.7.3, the TOML parser might only read the first matching section, or INI-style config parsers could encounter `SyntaxError`s due to `ast.literal_eval` leaks.
fix
Upgrade to v1.7.3 or later to benefit from fixes addressing these parsing inconsistencies and `SyntaxError` issues for TOML and INI formats.
affects: <1.7.3
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'configargparse'
The `configargparse` library has not been installed in the Python environment, or the environment where it's installed is not active.
fix
Install the library using pip: `pip install configargparse`
configargparse: error: unrecognized arguments: <config_file_path>
This error occurs when a configuration file path is provided on the command line, but the `configargparse.ArgumentParser` instance has not been configured to recognize it as a special config file argument using `is_config_file=True`.
fix
When defining the argument for the config file, set `is_config_file=True`. Example: `parser.add_argument('-c', '--config-file', is_config_file=True, help='Path to configuration file')`
yaml.parser.ParserError: while parsing a flow mapping
This error indicates a syntax issue within a YAML configuration file that `configargparse` is attempting to parse. Similar errors can occur with INI or TOML files if their syntax is incorrect for the respective parser.
fix
Review the specified YAML (or INI/TOML) configuration file for syntax errors, incorrect indentation, unquoted strings, or invalid character sequences. Ensure the file adheres to the YAML specification (or INI/TOML). For YAML, using a YAML linter can help identify issues.
configargparse: error: argument -i/--indexes: expected 2 arguments
This error typically arises when using an argument with `nargs > 1` (e.g., `nargs=2`) and `action='append'` in conjunction with a configuration file, where the values for the argument are not correctly formatted or are not providing the expected number of items per append operation within the config file.
fix
Ensure that the values for the `action='append'` argument with `nargs > 1` are specified as a list of lists or an equivalent structure in the config file, providing the correct number of items for each append. For example, in YAML: `indexes: [[2, 4], [1, 9]]`.
configargparse: error: the following arguments are required: <argument_name>
This error occurs when a `required=True` argument is not provided on the command line, even if a default value or a value in a config file might seem to satisfy it. By default, `required=True` checks for command-line presence.
fix
Either provide the required argument directly on the command line, or, if you intend for the config file value to satisfy the requirement, you might need to adjust the argument definition or logic to explicitly handle required values from config files, perhaps by making them not `required=True` but checking their presence after parsing.
Upgrade
Version history
1.7.5latest on PyPI · released Mar 11, 2026
Audit
Dependencies
PyYAMLoptionalRequired for YAML config file parsing (`YAMLConfigFileParser`).
tomloptionalRequired for TOML config file parsing (`TomlConfigParser`). (Note: Python 3.11+ includes `tomllib` which `configargparse` can use natively, but for older Python or explicit serialization, `toml` package is needed for full functionality).
Agent activity
22 hits · last 30 days
node
20
OpenAI (training)
1
Resources
configargparse — pip install configargparse · libregistry