Last modified: Aug 11, 2025 By Alexander Williams
Python Typer Boolean Flags and Multi-Value Options
Python Typer makes CLI development easy. This guide covers boolean flags and multi-value options.
Boolean Flags in Typer
Boolean flags are options that don't need values. They're either on or off.
Use typer.Option()
with default values to create them. Here's an example:
import typer
app = typer.Typer()
@app.command()
def greet(verbose: bool = typer.Option(False, "--verbose", "-v")):
if verbose:
typer.echo("Verbose mode activated!")
typer.echo("Hello World")
if __name__ == "__main__":
app()
Run it with or without the flag:
$ python app.py
Hello World
$ python app.py --verbose
Verbose mode activated!
Hello World
Important: The flag name determines if it's True or False. No value needed.
Multi-Value Options
Sometimes you need multiple values for an option. Typer supports this with multiple=True
.
This creates a list of values. Here's how to use it:
@app.command()
def process_files(files: list[str] = typer.Option(..., "--file", "-f", multiple=True)):
for file in files:
typer.echo(f"Processing {file}")
if __name__ == "__main__":
app()
Run it with multiple values:
$ python app.py --file a.txt --file b.txt
Processing a.txt
Processing b.txt
Combining Boolean and Multi-Value
You can combine these features for powerful CLIs. Here's an example:
@app.command()
def search(
query: list[str] = typer.Option(..., "--query", "-q", multiple=True),
case_sensitive: bool = typer.Option(False, "--case", "-c")
):
for q in query:
if case_sensitive:
typer.echo(f"Case-sensitive search: {q}")
else:
typer.echo(f"Search: {q.lower()}")
Try it with different combinations:
$ python app.py -q python -q typer
Search: python
Search: typer
$ python app.py -q Python -c
Case-sensitive search: Python
Best Practices
Follow these tips for better CLI design:
1. Use meaningful flag names. --verbose
is better than -v
alone.
2. Document your options. Add help text using the help
parameter.
3. Consider using help text to guide users.
4. For complex CLIs, explore subcommands.
Type Hints Matter
Typer uses type hints extensively. Always specify types for your options.
For boolean flags, use bool
. For multi-value, use list[str]
.
Learn more in our type hints guide.
Conclusion
Boolean flags and multi-value options make your CLI powerful. Typer handles them elegantly.
Remember to use proper type hints and document your options. This improves user experience.
For more advanced features, explore Typer's envvar
support or shell completion.