python-fire Documentation

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

28,222 stars Python Python 9 files ยท ~11,294 tokens #cli#python
RAW Doc

Technical Documentation: google/python-fire

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Python Fire [](https://github.com/google/python-fire)

Python Fire is a library for automatically generating command line interfaces
(CLIs) from absolutely any Python object.

  • Python Fire is a simple way to create a CLI in Python.
    [1]
  • Python Fire is a helpful tool for developing and debugging Python code.
    [2]
  • Python Fire helps with exploring existing code or turning other people's
    code into a CLI. [3]
  • Python Fire makes transitioning between Bash and Python easier.
    [4]
  • Python Fire makes using a Python REPL easier by setting up the REPL with the
    modules and variables you'll need already imported and created.
    [5]

Installation

To install Python Fire with pip, run: pip install fire

To install Python Fire with conda, run: conda install fire -c conda-forge

To install Python Fire from source, first clone the repository and then run:
python setup.py install

Basic Usage

You can call Fire on any Python object:
functions, classes, modules, objects, dictionaries, lists, tuples, etc.
They all work!

Here's an example of calling Fire on a function.

python
import fire

def hello(name="World"):
  return "Hello %s!" % name

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

Then, from the command line, you can run:

bash
python hello.py  # Hello World!
python hello.py --name=David  # Hello David!
python hello.py --help  # Shows usage information.

Here's an example of calling Fire on a class.

python
import fire

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

  def double(self, number):
    return 2 * number

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

Then, from the command line, you can run:

bash
python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

To learn how Fire behaves on functions, objects, dicts, lists, etc, and to learn
about Fire's other features, see the Using a Fire CLI page.

For additional examples, see The Python Fire Guide.

Why is it called Fire?

When you call Fire, it fires off (executes) your command.

Where can I learn more?

Please see The Python Fire Guide.

Reference

Setup Command Notes
install pip install fire
Creating a CLI Command Notes
import import fire
Call fire.Fire() Turns the current module into a Fire CLI.
Call fire.Fire(component) Turns component into a Fire CLI.
Using a CLI Command Notes
Help command --help or command -- --help
REPL command -- --interactive Enters interactive mode.
Separator command -- --separator=X Sets the separator to X. The default separator is -.
Completion command -- --completion [shell] Generates a completion script for the CLI.
Trace command -- --trace Gets a Fire trace for the command.
Verbose command -- --verbose

Note that these flags are separated from the Fire command by an isolated --.

License

Licensed under the
Apache 2.0 License.

Disclaimer

This is not an official Google product.


Overview (`fire/console/README.md`)

This is the console package from googlecloudsdk, as used by Python Fire.
Python Fire does not accept pull requests modifying the console package; rather,
changes to console should go through the upstream project googlecloudsdk.


Index (`docs/index.md`)

Python Fire [](https://github.com/google/python-fire)

Python Fire is a library for automatically generating command line interfaces
(CLIs) from absolutely any Python object.

  • Python Fire is a simple way to create a CLI in Python.
    [1]
  • Python Fire is a helpful tool for developing and debugging Python code.
    [2]
  • Python Fire helps with exploring existing code or turning other people's
    code into a CLI. [3]
  • Python Fire makes transitioning between Bash and Python easier.
    [4]
  • Python Fire makes using a Python REPL easier by setting up the REPL with the
    modules and variables you'll need already imported and created.
    [5]

Installation

To install Python Fire with pip, run: pip install fire

To install Python Fire with conda, run: conda install fire -c conda-forge

To install Python Fire from source, first clone the repository and then run:
python setup.py install

Basic Usage

You can call Fire on any Python object:
functions, classes, modules, objects, dictionaries, lists, tuples, etc.
They all work!

Here's an example of calling Fire on a function.

python
import fire

def hello(name="World"):
  return "Hello %s!" % name

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

Then, from the command line, you can run:

bash
python hello.py  # Hello World!
python hello.py --name=David  # Hello David!
python hello.py --help  # Shows usage information.

Here's an example of calling Fire on a class.

python
import fire

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

  def double(self, number):
    return 2 * number

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

Then, from the command line, you can run:

bash
python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

To learn how Fire behaves on functions, objects, dicts, lists, etc, and to learn
about Fire's other features, see the Using a Fire CLI page.

For additional examples, see The Python Fire Guide.

Why is it called Fire?

When you call Fire, it fires off (executes) your command.

Where can I learn more?

Please see The Python Fire Guide.

Reference

Setup Command Notes
install pip install fire
Creating a CLI Command Notes
import import fire
Call fire.Fire() Turns the current module into a Fire CLI.
Call fire.Fire(component) Turns component into a Fire CLI.
Using a CLI Command Notes
Help command --help or command -- --help
REPL command -- --interactive Enters interactive mode.
Separator command -- --separator=X Sets the separator to X. The default separator is -.
Completion command -- --completion [shell] Generates a completion script for the CLI.
Trace command -- --trace Gets a Fire trace for the command.
Verbose command -- --verbose

Note that flags are separated from the Fire command by an isolated -- arg.
Help is an exception; the isolated -- is optional for getting help.

License

Licensed under the
Apache 2.0 License.

Disclaimer

This is not an official Google product.


Api (`docs/api.md`)

Python Fire Quick Reference

Setup Command Notes
install pip install fire Installs fire from pypi
Creating a CLI Command Notes
import import fire
Call fire.Fire() Turns the current module into a Fire CLI.
Call fire.Fire(component) Turns component into a Fire CLI.
Using a CLI Command Notes
Help command --help Show the help screen.
REPL command -- --interactive Enters interactive mode.
Separator command -- --separator=X This sets the separator to X. The default separator is -.
Completion command -- --completion [shell] Generate a completion script for the CLI.
Trace command -- --trace Gets a Fire trace for the command.
Verbose command -- --verbose

Note that flags are separated from the Fire command by an isolated -- arg.
Help is an exception; the isolated -- is optional for getting help.

Arguments for Calling fire.Fire()

Argument Usage Notes
component fire.Fire(component) If omitted, defaults to a dict of all locals and globals.
command fire.Fire(command='hello --name=5') Either a string or a list of arguments. If a string is provided, it is split to determine the arguments. If a list or tuple is provided, they are the arguments. If command is omitted, then sys.argv[1:] (the arguments from the command line) are used by default.
name fire.Fire(name='tool') The name of the CLI, ideally the name users will enter to run the CLI. This name will be used in the CLI's help screens. If the argument is omitted, it will be inferred automatically.
serialize fire.Fire(serialize=custom_serializer) If omitted, simple types are serialized via their builtin str method, and any objects that define a custom __str__ method are serialized with that. If specified, all objects are serialized to text via the provided method.

Using a Fire CLI without modifying any code

You can use Python Fire on a module without modifying the code of the module.
The syntax for this is:

python -m fire <module> <arguments>

or

python -m fire <filepath> <arguments>

For example, python -m fire calendar -h will treat the built in calendar
module as a CLI and provide its help.


Benefits (`docs/benefits.md`)

Benefits of Python Fire

Create CLIs in Python

It's dead simple. Simply write the functionality you want exposed at the command
line as a function / module / class, and then call Fire. With this addition of a
single-line call to Fire, your CLI is ready to go.

Develop and debug Python code

When you're writing a Python library, you probably want to try it out as you go.
You could write a main method to check the functionality you're interested in,
but then you have to change the main method with every new experiment you're
interested in testing, and constantly updating the main method is a hassle.
You could also open an IPython REPL and import your library there and test it,
but then you have to deal with reloading your imports every time you change
something.

If you simply call Fire in your library, then you can run all of it's
functionality from the command line without having to keep making changes to
a main method. And if you use the --interactive flag to enter an IPython REPL
then you don't need to load the imports or create your variables; they'll
already be ready for use as soon as you start the REPL.

Explore existing code; turn other people's code into a CLI

You can take an existing module, maybe even one that you don't have access to
the source code for, and call Fire on it. This lets you easily see what
functionality this code exposes, without you having to read through all the
code.

This technique can be a very simple way to create very powerful CLIs. Call
Fire on the difflib library and you get a powerful diffing tool. Call Fire
on the Python Imaging Library (PIL) module and you get a powerful image
manipulation command line tool, very similar in nature to ImageMagick.

The auto-generated help strings that Fire provides when you run a Fire CLI
allow you to see all the functionality these modules provide in a concise
manner.

Transition between Bash and Python

Using Fire lets you call Python directly from Bash. So you can mix your Python
functions with the unix tools you know and love, like grep, xargs, wc,
etc.

Additionally since writing CLIs in Python requires only a single call to Fire,
it is now easy to write even one-off scripts that would previously have been in
Bash, in Python.

Explore code in a Python REPL

When you use the --interactive flag to enter an IPython REPL, it starts with
variables and modules already defined for you. You don't need to waste time
importing the modules you care about or defining the variables you're going to
use, since Fire has already done so for you.


Guide (`docs/guide.md`)

The Python Fire Guide

Introduction

Welcome to the Python Fire guide! Python Fire is a Python library that will turn
any Python component into a command line interface with just a single call to
Fire.

Let's get started!

Installation

To install Python Fire from pypi, run:

pip install fire

Alternatively, to install Python Fire from source, clone the source and run:

python setup.py install

Hello World

Version 1: `fire.Fire()`

The easiest way to use Fire is to take any Python program, and then simply call
fire.Fire() at the end of the program. This will expose the full contents of
the program to the command line.

python
import fire

def hello(name):
  return f'Hello {name}!'

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

Here's how we can run our program from the command line:

bash
$ python example.py hello World
Hello World!

Version 2: `fire.Fire()`

Let's modify our program slightly to only expose the hello function to the
command line.

python
import fire

def hello(name):
  return f'Hello {name}!'

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

Here's how we can run this from the command line:

bash
$ python example.py World
Hello World!

Notice we no longer have to specify to run the hello function, because we
called fire.Fire(hello).

Version 3: Using a main

We can alternatively write this program like this:

python
import fire

def hello(name):
  return f'Hello {name}!'

def main():
  fire.Fire(hello)

if __name__ == '__main__':
  main()

Or if we're using
entry points,
then simply this:

python
import fire

def hello(name):
  return f'Hello {name}!'

def main():
  fire.Fire(hello)

Version 4: Fire Without Code Changes

If you have a file example.py that doesn't even import fire:

python
def hello(name):
  return f'Hello {name}!'

Then you can use it with Fire like this:

bash
$ python -m fire example hello --name=World
Hello World!

You can also specify the filepath of example.py rather than its module path,
like so:

bash
$ python -m fire example.py hello --name=World
Hello World!

Exposing Multiple Commands

In the previous example, we exposed a single function to the command line. Now
we'll look at ways of exposing multiple functions to the command line.

Version 1: `fire.Fire()`

The simplest way to expose multiple commands is to write multiple functions, and
then call Fire.

python
import fire

def add(x, y):
  return x + y

def multiply(x, y):
  return x * y

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

We can use this like so:

bash
$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

You'll notice that Fire correctly parsed 10 and 20 as numbers, rather than
as strings. Read more about argument parsing here.

Version 2: `fire.Fire()`

In version 1 we exposed all the program's functionality to the command line. By
using a dict, we can selectively expose functions to the command line.

python
import fire

def add(x, y):
  return x + y

def multiply(x, y):
  return x * y

if __name__ == '__main__':
  fire.Fire({
      'add': add,
      'multiply': multiply,
  })

We can use this in the same way as before:

bash
$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

Version 3: `fire.Fire()`

Fire also works on objects, as in this variant. This is a good way to expose
multiple commands.

python
import fire

class Calculator(object):

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

  def multiply(self, x, y):
    return x * y

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

We can use this in the same way as before:

bash
$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

Version 4: `fire.Fire()`

Fire also works on classes. This is another good way to expose multiple
commands.

python
import fire

class Calculator(object):

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

  def multiply(self, x, y):
    return x * y

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

We can use this in the same way as before:

bash
$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

Why might you prefer a class over an object? One reason is that you can pass
arguments for constructing the class too, as in this broken calculator example.

python
import fire

class BrokenCalculator(object):

  def __init__(self, offset=1):
      self._offset = offset

  def add(self, x, y):
    return x + y + self._offset

  def multiply(self, x, y):
    return x * y + self._offset

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

When you use a broken calculator, you get wrong answers:

bash
$ python example.py add 10 20
31
$ python example.py multiply 10 20
201

But you can always fix it:

bash
$ python example.py add 10 20 --offset=0
30
$ python example.py multiply 10 20 --offset=0
200

Unlike calling ordinary functions, which can be done both with positional
arguments and named arguments (--flag syntax), arguments to __init__
functions must be passed with the --flag syntax. See the section on
calling functions for more.

Grouping Commands

Here's an example of how you might make a command line interface with grouped
commands.

python
class IngestionStage(object):

  def run(self):
    return 'Ingesting! Nom nom nom...'

class DigestionStage(object):

  def run(self, volume=1):
    return ' '.join(['Burp!'] * volume)

  def status(self):
    return 'Satiated.'

class Pipeline(object):

  def __init__(self):
    self.ingestion = IngestionStage()
    self.digestion = DigestionStage()

  def run(self):
    ingestion_output = self.ingestion.run()
    digestion_output = self.digestion.run()
    return [ingestion_output, digestion_output]

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

Here's how this looks at the command line:

bash
$ python example.py run
Ingesting! Nom nom nom...
Burp!
$ python example.py ingestion run
Ingesting! Nom nom nom...
$ python example.py digestion run
Burp!
$ python example.py digestion status
Satiated.

You can nest your commands in arbitrarily complex ways, if you're feeling grumpy
or adventurous.

Accessing Properties

In the examples we've looked at so far, our invocations of python example.py
have all run some function from the example program. In this example, we simply
access a property.

python
from airports import airports

import fire

class Airport(object):

  def __init__(self, code):
    self.code = code
    self.name = dict(airports).get(self.code)
    self.city = self.name.split(',')[0] if self.name else None

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

Now we can use this program to learn about airport codes!

bash
$ python example.py --code=JFK code
JFK
$ python example.py --code=SJC name
San Jose-Sunnyvale-Santa Clara, CA - Norman Y. Mineta San Jose International (SJC)
$ python example.py --code=ALB city
Albany-Schenectady-Troy

By the way, you can find this
airports module here.

Chaining Function Calls

When you run a Fire CLI, you can take all the same actions on the result of
the call to Fire that you can take on the original object passed in.

For example, we can use our Airport CLI from the previous example like this:

bash
$ python example.py --code=ALB city upper
ALBANY-SCHENECTADY-TROY

This works since upper is a method on all strings.

So, if you want to set up your functions to chain nicely, all you have to do is
have a class whose methods return self. Here's an example.

python
import fire

class BinaryCanvas(object):
  """A canvas with which to make binary art, one bit at a time."""

  def __init__(self, size=10):
    self.pixels = [[0] * size for _ in range(size)]
    self._size = size
    self._row = 0  # The row of the cursor.
    self._col = 0  # The column of the cursor.

  def __str__(self):
    return '\n'.join(' '.join(str(pixel) for pixel in row) for row in self.pixels)

  def show(self):
    print(self)
    return self

  def move(self, row, col):
    self._row = row % self._size
    self._col = col % self._size
    return self

  def on(self):
    return self.set(1)

  def off(self):
    return self.set(0)

  def set(self, value):
    self.pixels[self._row][self._col] = value
    return self

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

Now we can draw stuff :).

bash
$ python example.py move 3 3 on move 3 6 on move 6 3 on move 6 6 on move 7 4 on move 7 5 on
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

It's supposed to be a smiley face.

Custom Serialization

You'll notice in the BinaryCanvas example, the canvas with the smiley face was
printed to the screen. You can determine how a component will be serialized by
defining its __str__ method.

If a custom __str__ method is present on the final component, the object is
serialized and printed. If there's no custom __str__ method, then the help
screen for the object is shown instead.

Can we make an even simpler example than Hello World?

Yes, this program is even simpler than our original Hello World example.

python
import fire
english = 'Hello World'
spanish = 'Hola Mundo'
fire.Fire()

You can use it like this:

bash
$ python example.py english
Hello World
$ python example.py spanish
Hola Mundo

Calling Functions

Arguments to a constructor are passed by name using flag syntax --name=value.

For example, consider this simple class:

python
import fire

class Building(object):

  def __init__(self, name, stories=1):
    self.name = name
    self.stories = stories

  def climb_stairs(self, stairs_per_story=10):
    for story in range(self.stories):
      for stair in range(1, stairs_per_story):
        yield stair
      yield 'Phew!'
    yield 'Done!'

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

We can instantiate it as follows: python example.py --name="Sherrerd Hall"

Arguments to other functions may be passed positionally or by name using flag
syntax.

To instantiate a Building and then run the climb_stairs function, the
following commands are all valid:

bash
$ python example.py --name="Sherrerd Hall" --stories=3 climb_stairs 10
$ python example.py --name="Sherrerd Hall" climb_stairs --stairs_per_story=10
$ python example.py --name="Sherrerd Hall" climb_stairs --stairs-per-story 10
$ python example.py climb-stairs --stairs-per-story 10 --name="Sherrerd Hall"

You'll notice that hyphens and underscores (- and _) are interchangeable in
member names and flag names.

You'll also notice that the constructor's arguments can come after the
function's arguments or before the function.

You'll also notice that the equal sign between the flag name and its value is
optional.

Functions with `*varargs` and `**kwargs`

Fire supports functions that take *varargs or **kwargs. Here's an example:

python
import fire

def order_by_length(*items):
  """Orders items by length, breaking ties alphabetically."""
  sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item)))
  return ' '.join(sorted_items)

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

To use it, we run:

bash
$ python example.py dog cat elephant
cat dog elephant

You can use a separator to indicate that you're done providing arguments to a
function. All arguments after the separator will be used to process the result
of the function, rather than being passed to the function itself. The default
separator is the hyphen -.

Here's an example where we use a separator.

bash
$ python example.py dog cat elephant - upper
CAT DOG ELEPHANT

Without the separator, upper would have been treated as another argument.

bash
$ python example.py dog cat elephant upper
cat dog upper elephant

You can change the separator with the --separator flag. Flags are always
separated from your Fire command by an isolated --. Here's an example where we
change the separator.

bash
$ python example.py dog cat elephant X upper -- --separator=X
CAT DOG ELEPHANT

Separators can be useful when a function accepts *varargs, **kwargs, or
default values that you don't want to specify. It is also important to remember
to change the separator if you want to pass - as an argument.

Async Functions

Fire supports calling async functions too. Here's a simple example.

python
import asyncio

async def count_to_ten():
  for i in range(1, 11):
    await asyncio.sleep(1)
    print(i)

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

Whenever fire encounters a coroutine function, it runs it, blocking until it completes.

Argument Parsing

The types of the arguments are determined by their values, rather than by the
function signature where they're used. You can pass any Python literal from the
command line: numbers, strings, tuples, lists, dictionaries, (sets are only
supported in some versions of Python). You can also nest the collections
arbitrarily as long as they only contain literals.

To demonstrate this, we'll make a small example program that tells us the type
of any argument we give it:

python
import fire
fire.Fire(lambda obj: type(obj).__name__)

And we'll use it like so:

bash
$ python example.py 10
int
$ python example.py 10.0
float
$ python example.py hello
str
$ python example.py '(1,2)'
tuple
$ python example.py [1,2]
list
$ python example.py True
bool
$ python example.py {name:David}
dict

You'll notice in that last example that bare-words are automatically replaced
with strings.

Be careful with your quotes! If you want to pass the string "10", rather than
the int 10, you'll need to either escape or quote your quotes. Otherwise Bash
will eat your quotes and pass an unquoted 10 to your Python program, where
Fire will interpret it as a number.

bash
$ python example.py 10
int
$ python example.py "10"
int
$ python example.py '"10"'
str
$ python example.py "'10'"
str
$ python example.py \"10\"
str

Be careful with your quotes! Remember that Bash processes your arguments first,
and then Fire parses the result of that.
If you wanted to pass the dict {"name": "David Bieber"} to your program, you
might try this:

bash
$ python example.py '{"name": "David Bieber"}'  # Good! Do this.
dict
$ python example.py {"name":'"David Bieber"'}  # Okay.
dict
$ python example.py {"name":"David Bieber"}  # Wrong. This is parsed as a string.
str
$ python example.py {"name": "David Bieber"}  # Wrong. This isn't even treated as a single argument.
<error>
$ python example.py '{"name": "Justin Bieber"}'  # Wrong. This is not the Bieber you're looking for. (The syntax is fine though :))
dict

Boolean Arguments

The tokens True and False are parsed as boolean values.

You may also specify booleans via flag syntax --name and --noname, which set
name to True and False respectively.

Continuing the previous example, we could run any of the following:

bash
$ python example.py --obj=True
bool
$ python example.py --obj=False
bool
$ python example.py --obj
bool
$ python example.py --noobj
bool

Be careful with boolean flags! If a token other than another flag immediately
follows a flag that's supposed to be a boolean, the flag will take on the value
of the token rather than the boolean value. You can resolve this: by putting a
separator after your last flag, by explicitly stating the value of the boolean
flag (as in --obj=True), or by making sure there's another flag after any
boolean flag argument.

Using Fire Flags

Fire CLIs all come with a number of flags. These flags should be separated from
the Fire command by an isolated --. If there is at least one isolated --
argument, then arguments after the final isolated -- are treated as flags,
whereas all arguments before the final isolated -- are considered part of the
Fire command.

One useful flag is the --interactive flag. Use the --interactive flag on any
CLI to enter a Python REPL with all the modules and variables used in the
context where Fire was called already available to you for use. Other useful
variables, such as the result of the Fire command will also be available. Use
this feature like this: python example.py -- --interactive.

You can add the help flag to any command to see help and usage information. Fire
incorporates your docstrings into the help and usage information that it
generates. Fire will try to provide help even if you omit the isolated --
separating the flags from the Fire command, but may not always be able to, since
help is a valid argument name. Use this feature like this: python example.py -- --help or python example.py --help (or even python example.py -h).

The complete set of flags available is shown below, in the reference section.

Reference

Setup Command Notes
install pip install fire

Creating a CLI

Creating a CLI Command Notes
import import fire
Call fire.Fire() Turns the current module into a Fire CLI.
Call fire.Fire(component) Turns component into a Fire CLI.

Flags

Using a CLI Command Notes
Help command -- --help Show help and usage information for the command.
REPL command -- --interactive Enter interactive mode.
Separator command -- --separator=X This sets the separator to X. The default separator is -.
Completion command -- --completion [shell] Generate a completion script for the CLI.
Trace command -- --trace Gets a Fire trace for the command.
Verbose command -- --verbose Include private members in the output.

Note that flags are separated from the Fire command by an isolated -- arg.
Help is an exception; the isolated -- is optional for getting help.

Arguments for Calling fire.Fire()

Argument Usage Notes
component fire.Fire(component) If omitted, defaults to a dict of all locals and globals.
command fire.Fire(command='hello --name=5') Either a string or a list of arguments. If a string is provided, it is split to determine the arguments. If a list or tuple is provided, they are the arguments. If command is omitted, then sys.argv[1:] (the arguments from the command line) are used by default.
name fire.Fire(name='tool') The name of the CLI, ideally the name users will enter to run the CLI. This name will be used in the CLI's help screens. If the argument is omitted, it will be inferred automatically.
serialize fire.Fire(serialize=custom_serializer) If omitted, simple types are serialized via their builtin str method, and any objects that define a custom __str__ method are serialized with that. If specified, all objects are serialized to text via the provided method.

Disclaimer

Python Fire is not an official Google product.


Installation (`docs/installation.md`)

Installation

To install Python Fire with pip, run: pip install fire

To install Python Fire with conda, run: conda install fire -c conda-forge

To install Python Fire from source, first clone the repository and then run
python setup.py install. To install from source for development, instead run python setup.py develop.


Troubleshooting (`docs/troubleshooting.md`)

Troubleshooting

This page describes known issues that users of Python Fire have run into. If you
have an issue not resolved here, consider opening a
GitHub Issue.

Issue [#19](https://github.com/google/python-fire/issues/19): Don't name your module "cmd"

If you have a module name that conflicts with the name of a builtin module, then
when Fire goes to import the builtin module, it will import your module instead.
This will result in an error, possibly an AttributeError. Specifically, do not
name your module any of the following:
sys, linecache, cmd, bdb, repr, os, re, pprint, traceback


Using Cli (`docs/using-cli.md`)

Using a Fire CLI

Basic usage

Every Fire command corresponds to a Python component.

The simplest Fire command consists of running your program with no additional
arguments. This command corresponds to the Python component you called the
Fire function on. If you did not supply an object in the call to Fire, then
the context in which Fire was called will be used as the Python component.

You can append --help or -h to a command to see what Python component it
corresponds to, as well as the various ways in which you can extend the command.

Flags to Fire should be separated from the Fire command by an isolated -- in
order to distinguish between flags and named arguments. So, for example, to
enter interactive mode append -- -i or -- --interactive to any command. To
use Fire in verbose mode, append -- --verbose.

Given a Fire command that corresponds to a Python object, you can extend that
command to access a member of that object, call it with arguments if it is a
function, instantiate it if it is a class, or index into it if it is a list.

Read on to learn about how you can write a Fire command corresponding to
whatever Python component you're looking for.

Accessing members of an object

If your command corresponds to an object, you can extend your command by adding
the name of a member of that object as a new argument to the command. The
resulting command will correspond to that member.

For example, if the object your command corresponds to has a method defined on
it named 'whack', then you can add the argument 'whack' to your command, and the
resulting new command corresponds to the whack method.

As another example, if the object your command corresponds to has a property
named high_score, then you can add the argument 'high-score' to your command,
and the resulting new command corresponds to the value of the high_score
property.

Accessing members of a dict

If your command corresponds to a dict, you can extend your command by adding
the name of one of the dict's keys as an argument.

For example, widget function-that-returns-dict key will correspond to the
value of the item with key key in the dict returned by
function_that_returns_dict.

Accessing members of a list or tuple

If your command corresponds to a list or tuple, you can extend your command by
adding the index of an element of the component to your command as an argument.

For example, widget function-that-returns-list 2 will correspond to item 2 of
the result of function_that_returns_list.

Calling a function

If your command corresponds to a function, you can extend your command by adding
the arguments of this function. Arguments can be specified positionally, or by
name. To specify an argument by name, use flag syntax.

For example, suppose your command corresponds to the function double:

python
def double(value=0):
  return 2 * value

Then you can extend your command using named arguments as command --value 5,
or using positional arguments as command 5. In both cases, the new command
corresponds to the result of the function, in this case the number 10.

You can force a function that takes a variable number of arguments to be
evaluated by adding a separator (the default separator is the hyphen, "-"). This
will prevent arguments to the right of the separator from being consumed for
calling the function. This is useful if the function has arguments with default
values, or if the function accepts *varargs, or if the function accepts
**kwargs.

See also the section on Changing the Separator.

Instantiating a class

If your command corresponds to a class, you can extend your command by adding
the arguments of the class's __init__ function. Arguments must be specified
by name, using the flags syntax. See the section on
calling a function for more details.

Similarly, when passing arguments to a callable object (an object with a custom
__call__ function), those arguments must be passed using flags syntax.

Using Flags with Fire CLIs

Command line arguments to a Fire CLI are normally consumed by Fire, as described
in the Basic Usage section. In order to set Flags, put the flags
after the final standalone -- argument. (If there is no -- argument, then no
arguments are used for flags.)

For example, to set the alsologtostderr flag, you could run the command:
widget bang --noise=boom -- --alsologtostderr. The --noise argument is
consumed by Fire, but the --alsologtostderr argument is treated as a normal
Flag.

All CLIs built with Python Fire share some flags, as described in the next
sections.

Python Fire's Flags

As described in the Using Flags section, you must add an
isolated -- argument in order to have arguments treated as Flags rather than
be consumed by Python Fire. All arguments to a Fire CLI after the final
standalone -- argument are treated as Flags.

The following flags are accepted by all Fire CLIs:
--interactive/-i,
--help/-h,
--separator,
--completion,
--trace,
and --verbose/-v,
as described in the following sections.

`--interactive`: Interactive mode

Call widget -- --interactive or widget -- -i to enter interactive mode. This
will put you in an IPython REPL, with the variable widget already defined.

You can then explore the Python object that widget corresponds to
interactively using Python.

Note: if you want fire to start the IPython REPL instead of the regular Python one,
the ipython package needs to be installed in your environment.

`--completion`: Generating a completion script

Call widget -- --completion to generate a completion script for the Fire CLI
widget. To save the completion script to your home directory, you could e.g.
run widget -- --completion > ~/.widget-completion. You should then source this
file; to get permanent completion, source this file from your .bashrc file.

Call widget -- --completion fish to generate a completion script for the Fish
shell. Source this file from your fish.config.

If the commands available in the Fire CLI change, you'll have to regenerate the
completion script and source it again.

`--help`: Getting help

Let say you have a command line tool named widget that was made with Fire. How
do you use this Fire CLI?

The simplest way to get started is to run widget -- --help. This will give you
usage information for your CLI. You can always append -- --help to any Fire
command in order to get usage information for that command and any subcommands.

Additionally, help will be displayed if you hit an error using Fire. For
example, if you try to pass too many or too few arguments to a function, then
help will be displayed. Similarly, if you try to access a member that does not
exist, or if you index into a list with too high an index, then help will be
displayed.

The displayed help shows information about which Python component your command
corresponds to, as well as usage information for how to extend that command.

`--trace`: Getting a Fire trace

In order to understand what is happening when you call Python Fire, it can be
useful to request a trace. This is done via the --trace flag, e.g.
widget whack 5 -- --trace.

A trace provides step by step information about how the Fire command was
executed. In includes which actions were taken, starting with the initial
component, leading to the final component represented by the command.

A trace is also shown alongside the help if your Fire command reaches an error.

`--separator`: Changing the separator

As described in Calling a Function, you can use a
separator argument when writing a command that corresponds to calling a
function. The separator will cause the function to be evaluated or the class to
be instantiated using only the arguments left of the separator. Arguments right
of the separator will then be applied to the result of the function call or to
the instantiated object.

The default separator is -.

If you want to supply the string "-" as an argument, then you will have to
change the separator. You can choose a new separator by supplying the
--separator flag to Fire.

Here's an example to demonstrate separator usage. Let's say you have a function
that takes a variable number of args, and you want to call that function, and
then upper case the result. Here's how to do it:

python
# Here's the Python function
def display(arg1, arg2='!'):
  return arg1 + arg2
bash
# Here's what you can do from Bash (Note: the default separator is the hyphen -)
display hello                         # hello!
display hello upper                   # helloupper
display hello - upper                 # HELLO!
display - SEP upper -- --separator SEP    # -!

Notice how in the third and fourth lines, the separator caused the display
function to be called with the default value for arg2. In the fourth example,
we change the separator to the string "SEP" so that we can pass '-' as an
argument.

`--verbose`: Verbose usage

Adding the -v or --verbose flag turns on verbose mode. This will eg
reveal private members in the usage string. Often these members will not
actually be usable from the command line tool. As such, verbose mode should be
considered a debugging tool, but not fully supported yet.


--- METRICS ---