ArgBind

0.3.9 · active · verified Thu Apr 16

ArgBind is a compact Python library designed to simplify the binding of function or class arguments to the command line or YAML configuration files. It offers a scoping mechanism similar to frameworks like Hydra and gin-config, enabling the creation of complex and well-documented command-line programs. The library is small, comprising only around 400 lines of code, and is particularly useful for configuring machine learning experiments and other applications that benefit from flexible argument management. Its current version is 0.3.9.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a function with `argbind.bind()`, parse arguments (either defaults, command-line, or from a YAML file), and execute the bound function within an `argbind.scope` context. Arguments are prefixed with the function name (e.g., `--greet.name`).

import argbind

@argbind.bind()
def greet(name: str = 'World', excited: bool = False):
    """Greets the given name, optionally with excitement."""
    message = f"Hello, {name}"
    if excited:
        message += "!"
    print(message)

if __name__ == '__main__':
    # In a real CLI, this would parse sys.argv
    # For quickstart, simulate args or load from file
    
    # Example 1: Default execution
    print('--- Running with defaults ---')
    args_default = argbind.parse_args([]) # No CLI args provided
    with argbind.scope(args_default):
        greet()

    # Example 2: Override from simulated CLI args
    print('\n--- Running with CLI override ---')
    # Simulate `python your_script.py --greet.name Alice --greet.excited True`
    args_cli = argbind.parse_args(['--greet.name', 'Alice', '--greet.excited', 'True'])
    with argbind.scope(args_cli):
        greet()

    # Example 3: Load from a YAML file
    print('\n--- Running from YAML file ---')
    config_content = """
greet.name: Bob
greet.excited: False
"""
    with open('config.yaml', 'w') as f:
        f.write(config_content)

    args_yaml = argbind.load_args('config.yaml')
    with argbind.scope(args_yaml):
        greet()

    # Clean up (optional for quickstart, but good practice)
    import os
    os.remove('config.yaml')

view raw JSON →