Required CLI Options

We said before that by default:

  • CLI options are optional
  • CLI arguments are required

Well, that's how they work by default, and that's the convention in many CLI programs and systems.

But if you really want, you can change that.

To make a CLI option required, pass ... to typer.Option().

Info

If you hadn't seen that ... before: it is a special single value, it is part of Python and is called "Ellipsis".

That will tell Typer that it's still a CLI option, but it doesn't have a default value, and it's required.

Let's make --lastname a required CLI option:

import typer_cloup as typer


def main(name: str, lastname: str = typer.Option(...)):
    typer.echo(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

And test it:

// Pass the NAME CLI argument
$ python main.py Camila

// We didn't pass the now required --lastname CLI option
Usage: main.py [OPTIONS] NAME
Try "main.py --help" for help.

Error: Missing option '--lastname'.

// Now update it to pass the required --lastname CLI option
$ python main.py Camila --lastname Gutiérrez

Hello Camila Gutiérrez

// And if you check the help
$ python main.py --help

Usage: main.py [OPTIONS] NAME

Options:
  --lastname TEXT       [required]
  --help                Show this message and exit.

// It now tells you that --lastname is required 🎉
You can ask questions about Typer. Try:
How can I terminate a program?
How to launch applications?
How to add help to CLI argument?