Tab completion

Interfaces built with tyro.cli() can be tab completed in interactive shells without any source code modification.

Completion scripts can be generated by passing the --tyro-write-completion {bash/zsh/tcsh} PATH flag to a tyro CLI. This generates a completion script via shtab and writes it to a specified file. To set up tab completion, the printed script simply needs to be written somewhere where your shell will find it.

Zsh

For zsh, one option is to emulate the pattern used for completions in poetry:

# Set up zsh autocompletion for 01_functions.py, which is located in
# tyro/examples.

# (1) Make directory for local completions.
mkdir -p ~/.zfunc

# (2) Write completion script. The name here (_01_functions_py) doesn't matter,
# as long as it's prefixed with an underscore.
python 01_functions.py --tyro-write-completion zsh ~/.zfunc/_01_functions_py

And if it’s not in your .zshrc already:

# (3) Add .zfunc to our function search path, then initialize completions.
# Ideally this should go in your .zshrc!
fpath+=~/.zfunc
autoload -Uz compinit && compinit

Bash

Local completion scripts for bash can be written as described in the bash-complete documentation.

Q. Where should I install my own local completions?

A. Put them in the completions subdir of $BASH_COMPLETION_USER_DIR (defaults to $XDG_DATA_HOME/bash-completion or ~/.local/share/bash-completion if $XDG_DATA_HOME is not set) to have them loaded automatically on demand when the respective command is being completed […]

Borrowing from the bash-completion source[1], we can run:

# Set up bash autocompletion for 01_functions.py, which is located in
# tyro/examples.

# (1) Find and make completion directory.
completion_dir=${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions/
mkdir -p $completion_dir

# (2) Write completion scripts. The name of the completion script must match
# the name of the file.
python 01_functions.py --tyro-write-completion bash ${completion_dir}/01_functions.py

In contrast to zsh, tab completion in bash requires that scripts are either set up as an entry point or run as ./01_functions.py <TAB>, as opposed to with the python command, python 01_functions.py <TAB>.

Making a script directly executable typically requires:

  1. A permissions update: chmod +x ./01_functions.py.

  2. A shebang as the first line of your script: #!/usr/bin/env python