API Reference¶
Complete API documentation for argclass.
Quick Reference¶
Most users only need these:
What you want |
What to use |
|---|---|
Create a CLI parser |
|
Group related arguments |
|
Customize an argument |
|
Handle sensitive values |
|
Load config file argument |
|
Set log level argument |
|
Primary API¶
These are the main classes and functions you’ll use in most applications.
Parser¶
The base class for creating CLI parsers. Define arguments as class attributes with type hints.
import argclass
class MyApp(argclass.Parser):
name: str # Required argument
count: int = 1 # Optional with default
verbose: bool = False # Boolean flag
app = MyApp()
app.parse_args(["--name", "test"])
assert app.name == "test"
assert app.count == 1
assert app.verbose is False
- class argclass.Parser(config_files=(), auto_env_var_prefix=None, strict_config=False, config_parser_class=<class 'argclass.defaults.INIDefaultsParser'>, **kwargs)[source]¶
Bases:
AbstractParser,BaseMain parser class for command-line argument parsing.
- Parameters:
- HELP_APPENDIX_PREAMBLE = ' Default values will based on following configuration files {configs}. '¶
- HELP_APPENDIX_CURRENT = 'Now {num_existent} files has been applied {existent}. '¶
- HELP_APPENDIX_END = 'The configuration files is INI-formatted files where configuration groups is INI sections. See more https://docs.argclass.com/config-files.html'¶
- get_env_var(name, argument)[source]¶
- Parameters:
name (
str)argument (
TypedArgument)
- Return type:
- __init__(config_files=(), auto_env_var_prefix=None, strict_config=False, config_parser_class=<class 'argclass.defaults.INIDefaultsParser'>, **kwargs)[source]¶
- create_parser()[source]¶
Create an ArgumentParser instance without parsing arguments. Can be used to inspect the parser structure in external integrations. NOT AN ALTERNATIVE TO parse_args, because it does not back populates the parser attributes.
- Return type:
Group¶
Bundle related arguments under a common prefix. Groups can be reused across multiple parsers.
import argclass
class DatabaseGroup(argclass.Group):
host: str = "localhost"
port: int = 5432
class MyApp(argclass.Parser):
db = DatabaseGroup() # Arguments: --db-host, --db-port
app = MyApp()
app.parse_args(["--db-host", "prod.example.com"])
assert app.db.host == "prod.example.com"
assert app.db.port == 5432
Argument¶
Customize argument behavior: add help text, aliases, choices, and more.
import argclass
class MyApp(argclass.Parser):
name: str = argclass.Argument(
"-n", "--name",
help="User name",
)
level: str = argclass.Argument(
default="info",
choices=["debug", "info", "warning", "error"],
)
app = MyApp()
app.parse_args(["-n", "Alice", "--level", "debug"])
assert app.name == "Alice"
assert app.level == "debug"
- argclass.Argument(*aliases, action=Actions.STORE, choices=None, const=None, converter=None, default=None, env_var=None, help=None, metavar=None, nargs=None, required=None, secret=False, type=None)[source]¶
Create a typed argument for a Parser or Group class.
Dispatches to ArgumentSingle or ArgumentSequence based on nargs.
- Args:
aliases: Command-line aliases (e.g., “-n”, “–name”). action: How to handle the argument (store, store_true, etc.). choices: Restrict values to these options. const: Constant value for store_const/append_const actions. converter: Post-parse transform function. With nargs, receives the list. default: Default value if argument not provided. env_var: Environment variable to read default from. help: Help text for –help output. metavar: Placeholder name in help text. nargs: Number of values (int, “?”, “*”, “+”, or Nargs enum). required: Whether the argument must be provided. secret: If True, hide value from help and wrap str in SecretString. type: Per-value converter for argparse. With nargs, called per value.
- Returns:
TypedArgument instance.
Example:
# type: converts each CLI value individually numbers = Argument(nargs="+", type=int) # Parsing ["1", "2"] -> calls int("1"), int("2") -> [1, 2] # converter: transforms the final result after type conversion unique = Argument(nargs="+", type=int, converter=set) # Parsing ["1", "2", "1"] -> [1, 2, 1] -> set([1, 2, 1]) -> {1, 2} # Combining type and converter for set[int]: class Parser(argclass.Parser): numbers: set[int] = Argument( type=int, # Convert each "1", "2" to int converter=set, # Convert [1, 2, 1] to {1, 2} nargs="+", ) # Alternative: single converter function for set[int]: class Parser(argclass.Parser): numbers: set[int] = Argument( converter=lambda vals: set(map(int, vals)), nargs="+", )
Secret¶
Handle sensitive values that should be masked in logs and removed from environment after parsing.
import os
import argclass
os.environ["TEST_API_KEY"] = "secret123"
class MyApp(argclass.Parser):
api_key: str = argclass.Secret(env_var="TEST_API_KEY")
app = MyApp()
# Use sanitize_secrets=True to auto-remove secret env vars during parsing
app.parse_args([], sanitize_secrets=True)
assert str(app.api_key) == "******" # Masked in string representation
assert app.api_key == "secret123" # But actual value is accessible
assert "TEST_API_KEY" not in os.environ # Already removed
Alternatively, call sanitize_env() manually after parsing:
import os
import argclass
os.environ["TEST_API_KEY"] = "secret123"
class MyApp(argclass.Parser):
api_key: str = argclass.Secret(env_var="TEST_API_KEY")
app = MyApp()
app.parse_args([])
app.sanitize_env() # Remove all used env vars
assert "TEST_API_KEY" not in os.environ
# Or use: app.sanitize_env(only_secrets=True) to keep non-secret env vars
- argclass.Secret(*aliases, action=Actions.STORE, choices=None, const=None, converter=None, default=None, env_var=None, help=None, metavar=None, nargs=None, required=None, type=None)[source]¶
Create a secret argument that masks sensitive values.
Secret arguments are wrapped in SecretString, which:
Returns
'******'for repr() to prevent accidental loggingSupports equality comparison without exposing the value
Use str() to access the actual value when needed
Use
parser.sanitize_env()after parsing to remove secret environment variables before spawning subprocesses.- Args:
aliases: Command-line aliases (e.g., “-p”, “–password”). env_var: Environment variable to read the secret from. default: Default value if not provided. help: Help text (the actual value is never shown).
- Returns:
TypedArgument with secret=True.
Example:
class Parser(argclass.Parser): api_key: str = argclass.Secret(env_var="API_KEY") password: str = argclass.Secret() parser = Parser() parser.parse_args() parser.sanitize_env() # Remove secrets from environment # Safe: shows '******' print(f"API key: {parser.api_key!r}") # Access actual value connect(api_key=str(parser.api_key))
SecretString¶
The type returned for Secret arguments. Masks value in str() and repr().
- class argclass.SecretString[source]¶
Bases:
strThe class mimics the string, with one important difference. Attempting to call __str__ of this instance will result in the output of placeholer (the default is “**”) if the call stack contains of logging module. In other words, this is an attempt to keep secrets out of the log.
However, if you try to do an f-string or str() at the moment the parameter is passed to the log, the value will be received, because there is nothing about logging in the stack.
The repr will always give placeholder, so it is better to always add
!rfor any f-string, for example f’{value!r}’.Examples:
>>> import logging >>> from argclass import SecretString >>> logging.basicConfig(level=logging.INFO) >>> s = SecretString("my-secret-password") >>> logging.info(s) # __str__ will be called from logging INFO:root:'******' >>> logging.info(f"s=%s", s) # __str__ will be called from logging too INFO:root:s='******' >>> logging.info(f"{s!r}") # repr is safe INFO:root:'******' >>> logging.info(f"{s}") # the password will be compromised INFO:root:my-secret-password
- PLACEHOLDER = '******'¶
- MODULES_SKIPLIST = ('logging', 'log.py')¶
Configuration Files¶
Load defaults from INI, JSON, or TOML configuration files.
Config¶
Add a --config argument that loads structured data from a file.
Access values via dict-like interface (parser.config["key"]).
import argclass
from pathlib import Path
from tempfile import NamedTemporaryFile
class MyApp(argclass.Parser):
config = argclass.Config(config_class=argclass.JSONConfig)
verbose: bool = False
# Create a temporary config file
with NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
f.write('{"database": {"host": "example.com", "port": 9000}}')
config_path = f.name
app = MyApp()
app.parse_args(["--config", config_path])
# Access config data via dict-like interface
assert app.config["database"]["host"] == "example.com"
assert app.config["database"]["port"] == 9000
Path(config_path).unlink()
Tip
For loading defaults into parser attributes, use config_files parameter instead.
See Config File Parsers.
- argclass.Config(*aliases, search_paths=None, choices=None, converter=None, const=None, default=None, env_var=None, help=None, metavar=None, nargs=None, required=None, config_class=<class 'argclass.store.INIConfig'>)[source]¶
Create a configuration file argument.
This creates a
--configargument that loads structured data from a file. The loaded data is accessible as a dict-like object.- Note:
This is different from
config_filesparameter on Parser, which presets CLI argument defaults. This argument loads arbitrary configuration data for your application.- Args:
aliases: Command-line aliases (default: “–config”). search_paths: Default paths to search for config files. config_class: Parser class (INIConfig, JSONConfig, TOMLConfig). env_var: Environment variable for config file path. help: Help text for –help output.
- Returns:
ConfigArgument instance.
Example:
class Parser(argclass.Parser): config = argclass.Config(config_class=argclass.JSONConfig) parser = Parser() parser.parse_args(["--config", "settings.json"]) # Access loaded configuration db_host = parser.config["database"]["host"]
Config Argument Classes¶
Class |
Format |
Usage |
|---|---|---|
|
INI files |
|
|
JSON files |
|
|
TOML files |
|
- class argclass.INIConfig(**kwargs)[source]¶
Bases:
ConfigArgumentParse INI file and set results as a value.
- Parameters:
kwargs (
Any)
- action¶
alias of
INIConfigAction
- class argclass.JSONConfig(**kwargs)[source]¶
Bases:
ConfigArgumentParse JSON file and set results as a value.
- Parameters:
kwargs (
Any)
- action¶
alias of
JSONConfigAction
Note
TOML requires tomllib (Python 3.11+) or tomli package (Python 3.10).
- class argclass.TOMLConfig(**kwargs)[source]¶
Bases:
ConfigArgumentParse TOML file and set results as a value.
Uses stdlib tomllib (Python 3.11+) or tomli package as fallback.
- Parameters:
kwargs (
Any)
- action¶
alias of
TOMLConfigAction
Config File Parsers¶
Used with config_parser_class parameter in Parser() to load defaults
from config files at parser initialization.
import argclass
from pathlib import Path
from tempfile import NamedTemporaryFile
class MyApp(argclass.Parser):
host: str = "localhost"
port: int = 8080
# Create a temporary config file
with NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
f.write('{"host": "db.example.com", "port": 5432}')
config_path = f.name
app = MyApp(
config_files=[config_path],
config_parser_class=argclass.JSONDefaultsParser,
)
app.parse_args([])
assert app.host == "db.example.com"
assert app.port == 5432
Path(config_path).unlink()
Class |
Format |
|---|---|
|
INI files (default) |
|
JSON files |
|
TOML files |
- class argclass.INIDefaultsParser(paths, strict=False)[source]¶
Bases:
AbstractDefaultsParserParse INI configuration files for default values.
This is the default parser used by argclass. It uses Python’s configparser module to read INI files.
INI sections map to argument groups, and the [DEFAULT] section contains top-level argument defaults.
Values that look like Python literals (lists, bools) are converted when requested via get_value() with appropriate ValueKind.
- BOOL_TRUE_VALUES = frozenset({'1', 'enable', 'enabled', 'on', 't', 'true', 'y', 'yes'})¶
- class argclass.JSONDefaultsParser(paths, strict=False)[source]¶
Bases:
AbstractDefaultsParserParse JSON configuration files for default values.
The JSON structure should be a flat or nested object where: - Top-level keys are argument names or group names - Group values are objects with argument names as keys
JSON natively supports lists and booleans, so no conversion needed.
- class argclass.TOMLDefaultsParser(paths, strict=False)[source]¶
Bases:
AbstractDefaultsParserParse TOML configuration files for default values.
Uses stdlib tomllib (Python 3.11+) or tomli package as fallback.
The TOML structure should be: - Top-level keys are argument names - Tables (sections) map to argument groups
TOML natively supports lists and booleans, so no conversion needed.
Pre-built Arguments¶
LogLevel¶
A pre-configured argument for log levels. Accepts level names and returns
the corresponding logging module constant.
import argclass
import logging
class MyApp(argclass.Parser):
log_level: int = argclass.LogLevel
app = MyApp()
app.parse_args(["--log-level", "debug"])
assert app.log_level == logging.DEBUG
app.parse_args(["--log-level", "WARNING"])
assert app.log_level == logging.WARNING
Accepts: debug, info, warning, error, critical (case-insensitive).
Enums and Constants¶
Actions¶
Argument actions (mirrors argparse actions).
Action |
Description |
|---|---|
|
Store the value (default) |
|
Store |
|
Store |
|
Append value to a list |
|
Count occurrences |
Nargs¶
Number of arguments constants.
Value |
Meaning |
|---|---|
|
Zero or one argument |
|
Zero or more arguments |
|
One or more arguments |
Utility Functions¶
parse_bool¶
Parse boolean strings from environment variables or config files.
from argclass import parse_bool
assert parse_bool("true") is True
assert parse_bool("yes") is True
assert parse_bool("1") is True
assert parse_bool("on") is True
assert parse_bool("false") is False
assert parse_bool("no") is False
assert parse_bool("0") is False
assert parse_bool("off") is False
read_configs¶
Read and merge multiple configuration files.
Exceptions¶
argclass provides a hierarchy of typed exceptions for debugging configuration and parsing errors. All exceptions include structured context attributes.
ArgclassError¶
Base exception for all argclass errors. Provides field_name and hint
attributes for debugging context.
- class argclass.ArgclassError(message, *, field_name=None, hint=None)[source]¶
Bases:
ExceptionBase exception for all argclass errors.
Provides structured context for debugging configuration issues. All argclass exceptions inherit from this class.
- Attributes:
message: The error message describing what went wrong. field_name: The name of the field that caused the error, if applicable. hint: A suggestion for how to fix the error, if available.
Example:
try: # ... argclass operation that may fail pass except ArgclassError as e: print(f"Error: {e}") if e.field_name: print(f"Field: {e.field_name}") if e.hint: print(f"Hint: {e.hint}")
ArgumentDefinitionError¶
Raised when an argument cannot be added to the parser due to invalid configuration, such as conflicting option strings or invalid argparse kwargs.
- class argclass.ArgumentDefinitionError(message, *, field_name=None, aliases=None, kwargs=None, hint=None)[source]¶
Bases:
ArgclassErrorError in argument definition or registration with argparse.
Raised when an argument cannot be added to the parser due to invalid configuration (conflicting options, invalid types, etc.).
- Attributes:
aliases: The conflicting aliases, e.g.,
("-v", "--verbose"). kwargs: The kwargs passed to argparse when the error occurred.
Example:
# This exception is typically raised during parser construction # when argument definitions conflict: try: class Parser(argclass.Parser): verbose: bool = argclass.Argument("-h") # conflicts with --help except ArgumentDefinitionError as e: print(f"Conflict: {e.aliases}")
- Parameters:
TypeConversionError¶
Raised when a value cannot be converted to the expected type. Includes the
original value and target_type for debugging.
- class argclass.TypeConversionError(message, *, field_name=None, value=None, target_type=None, hint=None)[source]¶
Bases:
ArgclassErrorError during type conversion of argument values.
Raised when a value cannot be converted to the expected type, either by the type function or a custom converter.
- Attributes:
value: The original value that failed conversion. target_type: The type that the value was being converted to.
Example:
try: # When a custom converter fails: def strict_port(value: str) -> int: port = int(value) if not (1 <= port <= 65535): raise TypeConversionError( "Port must be between 1 and 65535", field_name="port", value=value, target_type=int, hint="Use a valid port number (1-65535)", ) return port except TypeConversionError as e: print(f"Invalid value: {e.value!r} for type {e.target_type}")
- Parameters:
ConfigurationError¶
Raised when a configuration file cannot be parsed or contains values that
don’t match expected types. Includes file_path and section attributes.
- class argclass.ConfigurationError(message, *, field_name=None, file_path=None, section=None, hint=None)[source]¶
Bases:
ArgclassErrorError loading or parsing configuration files.
Raised when a configuration file cannot be parsed or contains invalid values for the expected argument types.
- Attributes:
file_path: Path to the configuration file that caused the error. section: The config section (e.g., INI section) where error occurred.
Example:
try: parser = Parser( config_files=["config.ini"], config_parser_class=argclass.INIDefaultsParser, ) except ConfigurationError as e: print(f"Config error in {e.file_path}") if e.section: print(f"Section: [{e.section}]")
- Parameters:
EnumValueError¶
Raised when an enum default or parsed value is not a valid member of the
specified enum class. Includes enum_class and valid_values for diagnostics.
- class argclass.EnumValueError(message, *, field_name=None, enum_class=None, valid_values=None, hint=None)[source]¶
Bases:
ArgclassErrorError with enum argument value or default.
Raised when an enum default or value is not a valid member of the specified enum class.
- Attributes:
enum_class: The enum class that was expected. valid_values: Tuple of valid enum member names.
Example:
from enum import Enum class Color(Enum): RED = "red" GREEN = "green" try: class Parser(argclass.Parser): # "YELLOW" is not a valid Color member color: Color = argclass.EnumArgument(Color, default="YELLOW") except EnumValueError as e: print(f"Invalid value for {e.enum_class.__name__}") print(f"Valid options: {', '.join(e.valid_values)}")
- Parameters:
ComplexTypeError¶
Raised when a type annotation is too complex to be automatically handled
(e.g., Union[str, int]) and requires an explicit converter.
- class argclass.ComplexTypeError(message, *, field_name=None, typespec=None, hint=None)[source]¶
Bases:
ArgclassErrorError with complex type annotations.
Raised when a type annotation is too complex to be automatically handled and requires explicit converter specification.
- Attributes:
typespec: The type annotation that could not be handled.
Example:
try: class Parser(argclass.Parser): # Union types (other than T | None) are not supported value: str | int # Raises ComplexTypeError except ComplexTypeError as e: print(f"Cannot handle type: {e.typespec}") print("Provide an explicit converter with type=...")
Advanced / Internal¶
These classes are primarily for advanced use cases or extending argclass.
Base¶
Abstract base class for both Parser and Group.
AbstractDefaultsParser¶
Base class for implementing custom config file parsers.
- class argclass.AbstractDefaultsParser(paths, strict=False)[source]¶
Bases:
ABCAbstract base class for parsing configuration files into defaults.
Subclass this to implement custom configuration file formats for the config_files parameter of Parser.
- abstractmethod parse()[source]¶
Parse configuration files and return defaults mapping.
- Returns:
A mapping where keys are argument names or group names, and values are either default values (str) or nested mappings for groups.
- get_value(key, kind=ValueKind.STRING, section=None)[source]¶
Get value with type validation.
- Args:
key: The config key name. kind: Expected value type for validation. section: Optional section/group name for nested values.
- Returns:
The value, converted if necessary (e.g., INI literal_eval).
- Raises:
UnexpectedConfigValue: If value doesn’t match expected kind.
ValueKind¶
Enum specifying expected value types for config file loading.
Value |
Description |
|---|---|
|
Default, no conversion |
|
Lists/tuples or any iterable container |
|
Boolean values |
UnexpectedConfigValue¶
Exception raised when a config value doesn’t match the expected type.
ConfigArgument¶
Base class for config file argument types.
ConfigAction¶
Action class for config file arguments.
- class argclass.ConfigAction(option_strings, dest, search_paths=(), type=mappingproxy({}), help='', required=False, default=None)[source]¶
Bases:
ActionBase action for loading configuration files.
- Parameters:
TypedArgument¶
Internal class representing a typed argument.
Store¶
Internal storage for argument metadata.
Specialized Argument Functions¶
- argclass.ArgumentSingle(*aliases, type, action=Actions.STORE, choices=None, const=None, converter=None, default=None, env_var=None, help=None, metavar=None, required=None, secret=False)[source]¶
Create a single-value argument with precise typing.
Use this when you need exact type inference for a single value. The type parameter is required and determines the return type.
- Example:
- class Parser(argclass.Parser):
count: int = argclass.ArgumentSingle(type=int, default=10) name: str = argclass.ArgumentSingle(type=str)
- argclass.ArgumentSequence(*aliases, type, nargs=Nargs.ONE_OR_MORE, action=Actions.STORE, choices=None, const=None, converter=None, default=None, env_var=None, help=None, metavar=None, required=None, secret=False)[source]¶
Create a multi-value argument with precise typing.
Use this when you need exact type inference for a list of values. The
typeparameter is required and determines the element type.- Args:
- nargs: Number of values. Defaults to “+” (one or more).
Use “*” for zero or more, or an int for exact count.
Example:
class Parser(argclass.Parser): files: list[str] = argclass.ArgumentSequence(type=str) numbers: list[int] = argclass.ArgumentSequence( type=int, nargs="*", default=[] )
EnumArgument¶
Create arguments from Enum classes with automatic choice validation.
import argclass
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
class MyApp(argclass.Parser):
# Default can be enum member or string name
priority: Priority = argclass.EnumArgument(
Priority, default="MEDIUM"
)
app = MyApp()
app.parse_args([])
assert app.priority == Priority.MEDIUM
app.parse_args(["--priority", "HIGH"])
assert app.priority == Priority.HIGH
Use lowercase=True for case-insensitive input:
import argclass
from enum import IntEnum
class Level(IntEnum):
DEBUG = 10
INFO = 20
WARNING = 30
class MyApp(argclass.Parser):
level: Level = argclass.EnumArgument(
Level, default="info", lowercase=True
)
app = MyApp()
app.parse_args([])
assert app.level == Level.INFO
# Accepts lowercase input
app.parse_args(["--level", "debug"])
assert app.level == Level.DEBUG
- argclass.EnumArgument(enum_class, *aliases, action=Actions.STORE, default=None, env_var=None, help=None, metavar=None, nargs=None, required=None, use_value=False, lowercase=False)[source]¶
Create an argument from an Enum class.
- Args:
enum_class: The Enum class to use for choices and conversion. aliases: Command-line aliases (e.g., “-l”, “–level”). action: How to handle the argument. default: Default value as enum member or string name. env_var: Environment variable to read default from. help: Help text for –help output. metavar: Placeholder name in help text. nargs: Number of values. required: Whether the argument must be provided. use_value: If True, return enum.value instead of enum member. lowercase: If True, use lowercase choices and accept lowercase input.
- Returns:
TypedArgument instance.