Python Fire

Language: Python

CLI/Utils

Python Fire was created by Google in 2017 to make it easy to turn existing Python code into CLI tools. It allows developers to quickly expose functionality without writing repetitive argument parsing code, making it popular for scripting, automation, and testing.

Python Fire is a library for automatically generating command-line interfaces (CLIs) from any Python object, such as functions, classes, or dictionaries. It enables rapid CLI creation without boilerplate code.

Installation

pip: pip install fire
conda: conda install -c conda-forge python-fire

Usage

Python Fire generates a CLI automatically from Python code. It parses command-line arguments and maps them to function parameters, class methods, or dictionary keys. It supports nested objects and provides help and error messages automatically.

Creating a CLI from a function

import fire

def greet(name='World'):
    return f'Hello, {name}!'

if __name__ == '__main__':
    fire.Fire(greet)

Generates a command-line interface where you can run `python script.py --name Alice` to print `Hello, Alice!`.

Creating a CLI from a class

import fire

class Calculator:
    def add(self, x, y):
        return x + y

if __name__ == '__main__':
    fire.Fire(Calculator)

Generates a CLI from the `Calculator` class. You can run `python script.py add 3 5` to get `8`.

Nested commands

import fire

class Math:
    class Operations:
        @staticmethod
        def multiply(x, y):
            return x * y

if __name__ == '__main__':
    fire.Fire(Math)

Supports nested objects. You can run `python script.py Operations multiply 3 4` to get `12`.

Using dictionaries

import fire

config = {
    'host': 'localhost',
    'port': 8080
}

if __name__ == '__main__':
    fire.Fire(config)

Exposes a dictionary as a CLI. Running `python script.py host` prints `localhost`.

Customizing CLI behavior

import fire

class App:
    def run(self, debug=False):
        print(f'Running app with debug={debug}')

if __name__ == '__main__':
    fire.Fire(App)

Supports flags and optional arguments. Running `python script.py run --debug True` enables debug mode.

Error Handling

TypeError: Missing required positional argument: Ensure that all required function parameters are provided in the CLI call.
FireError: Unsupported type: Python Fire may not handle certain types; convert objects to standard Python types (str, int, float, list, dict) before exposing.

Best Practices

Use Python Fire for quick CLI tools without manually parsing arguments.

Avoid exposing sensitive functions or credentials via Fire CLIs.

Keep CLI entry points simple and delegate complex logic to underlying functions or classes.

Use docstrings to provide helpful documentation for automatically generated CLI help.

Combine Fire with logging or exception handling for robust command-line tools.