← Back to google/python-fire

How to Deploy & Use google/python-fire

Python Fire Deployment & Usage Guide

A comprehensive guide for installing, developing with, and deploying Python Fire—a library for automatically generating command line interfaces (CLIs) from any Python object.


1. Prerequisites

Before installing Python Fire, ensure you have:

  • Python: Version 3.7 or higher (check with python --version or python3 --version)
  • pip: Usually included with Python (check with pip --version)
  • Virtual environment (recommended): venv or virtualenv for isolation
  • Git (optional): Only required for source installation or contributing

Verify Environment

python --version  # Should be 3.7+
pip --version

2. Installation

Choose one of the following methods:

Option A: Install from PyPI (Recommended)

pip install fire

Option B: Install with Conda

conda install fire -c conda-forge

Option C: Install from Source

git clone https://github.com/google/python-fire.git
cd python-fire
python setup.py install

Option D: Development Installation (Editable)

For contributing or modifying the library:

git clone https://github.com/google/python-fire.git
cd python-fire
pip install -e .

Verify Installation

python -c "import fire; print(fire.__version__)"

3. Configuration

Python Fire requires minimal configuration. Optional setups include:

Shell Completion (Optional)

Generate completion scripts for your shell:

# After creating a Fire CLI, run:
python your_script.py -- --completion bash > /path/to/completions/your_script.sh
# Or for zsh:
python your_script.py -- --completion zsh

Development Environment

If installing from source, ensure the fire package is in your Python path:

export PYTHONPATH="${PYTHONPATH}:$(pwd)"

No Configuration Files Required

Fire does not use external configuration files (JSON, YAML, etc.). All behavior is controlled through:

  • Python code (docstrings, function signatures)
  • Command-line flags (see Section 4)

4. Build & Run

Since Python Fire is a library, "building" means creating CLI scripts. Here are practical patterns:

Basic Function CLI

Create hello.py:

import fire

def hello(name="World"):
  """Says hello to the specified name."""
  return f"Hello {name}!"

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

Run it:

# Default value
python hello.py
# Output: Hello World!

# Positional argument
python hello.py David
# Output: Hello David!

# Named argument
python hello.py --name=David
# Output: Hello David!

# Get help
python hello.py --help

Class-Based CLI

Create calculator.py:

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    """Doubles the input number."""
    return 2 * number
  
  def add(self, a, b):
    """Adds two numbers."""
    return a + b

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

Run it:

# Call methods
python calculator.py double 10
# Output: 20

python calculator.py add --a=5 --b=3
# Output: 8

# Access help
python calculator.py --help
python calculator.py double --help

Module-Level CLI

Create mymodule.py:

import fire

def function_a():
  return "Function A"

def function_b():
  return "Function B"

if __name__ == '__main__':
  fire.Fire()  # Exposes all module-level functions

Fire CLI Flags

All Fire-generated CLIs support these flags (must follow isolated --):

FlagCommandPurpose
Help-- --help or -hShow detailed help
Interactive-- --interactive or -iDrop into Python REPL after execution
Verbose-- --verbose or -vInclude private members in help
Trace-- --traceShow Fire trace for debugging
Separator-- --separator=XChange separator (default: -)

Example:

python calculator.py double 10 -- --interactive
# Runs the command, then opens REPL with results available

5. Deployment

Deploy Python Fire in three contexts: as a dependency, as a distributed CLI tool, or as a containerized application.

As a Project Dependency

Add to requirements.txt:

fire>=0.5.0

Or in setup.py for your own package:

install_requires=[
    'fire>=0.5.0',
],

Distributing a Fire CLI Tool

To distribute your Fire-based CLI to other users:

  1. Package Structure:
mycli/
├── mycli/
│   ├── __init__.py
│   └── main.py          # Contains fire.Fire() call
├── setup.py
└── requirements.txt
  1. Entry Points in setup.py:
from setuptools import setup

setup(
    name='mycli',
    version='0.1',
    py_modules=['mycli'],
    install_requires=['fire'],
    entry_points={
        'console_scripts': [
            'mycli=mycli.main:main',  # Assumes main() calls fire.Fire()
        ],
    },
)
  1. Build and Publish:
pip install setuptools wheel twine
python setup.py sdist bdist_wheel
twine upload dist/*

Container Deployment

Create a Dockerfile for your Fire CLI:

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
RUN pip install .

ENTRYPOINT ["python", "-m", "your_module"]

Build and run:

docker build -t my-fire-cli .
docker run my-fire-cli double 10

Cloud Function Deployment

Fire works well with Google Cloud Functions or AWS Lambda:

import fire

def handler(request):
    # Convert HTTP request to Fire CLI call
    import shlex
    args = shlex.split(request.args.get('command', ''))
    fire.Fire(YourClass, command=args)
    return "OK"

6. Troubleshooting

ImportError: No module named 'fire'

Cause: Python Fire not installed in current environment
Solution:

pip install fire
# Or if using multiple Python versions:
python3 -m pip install fire

Arguments not parsed correctly

Symptom: Arguments with spaces or special characters fail
Solution: Use quotes or equals signs:

# Bad
python script.py --name=John Doe

# Good
python script.py --name="John Doe"
# Or
python script.py --name="John Doe"

Fire flags not recognized

Symptom: --help returns "unrecognized arguments"
Cause: Fire flags must follow isolated --
Solution:

# Wrong
python script.py --help

# Right
python script.py -- --help

Interactive mode not working

Symptom: -- --interactive drops to REPL but variables not available
Solution: Ensure you're using the correct separator:

python script.py command args -- --interactive

Type conversion issues

Symptom: Numeric arguments treated as strings
Solution: Fire uses Python's type hints or docstrings. Add type hints:

def add(a: int, b: int) -> int:
    return a + b

Private methods showing in help

Symptom: Methods starting with _ appear in help text
Solution: Use -- --verbose only when needed, or exclude with naming conventions. By default, Fire hides private members unless verbose mode is enabled.

Module not found when running

Symptom: ModuleNotFoundError for your own modules
Solution: Use editable install during development:

pip install -e .

Quick Reference

# Install
pip install fire

# Basic usage template
import fire
fire.Fire(Component)

# Run with help
python script.py -- --help

# Run with REPL
python script.py -- --interactive

# Development install
pip install -e .