Printing and Colors

You can use typer.echo() to print to the screen:

import typer


def main():
    typer.echo("Hello World")


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

The reason to use typer.echo() instead of just print() is that it applies some error corrections in case the terminal is misconfigured, and it will properly output color if it's supported.

Info

typer.echo() comes directly from Click, you can read more about it in Click's docs.

Check it:

$ python main.py

Hello World

Color

Info

For colors to work correctly on Windows you need to also install colorama.

You don't need to call colorama.init(). Typer (actually Click) will handle it underneath.

Technical Details

The way color works in terminals is by using some codes (ASCII codes) as part of the text.

So, a colored text is still just a str.

You can create colored strings to output to the terminal with typer.style(), that gives you strs that you can then pass to typer.echo():

import typer


def main(good: bool = True):
    message_start = "everything is "
    if good:
        ending = typer.style("good", fg=typer.colors.GREEN, bold=True)
    else:
        ending = typer.style("bad", fg=typer.colors.WHITE, bg=typer.colors.RED)
    message = message_start + ending
    typer.echo(message)


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

Tip

The parameters fg and bg receive strings with the color names. You could simply pass fg="green" and bg="red".

But Typer provides them all as variables like typer.colors.GREEN just so you can use autocompletion while selecting them.

Check it:

python main.py everything is good python main.py --no-good everything is bad

You can pass these function arguments to typer.style():

  • fg: the foreground color.
  • bg: the background color.
  • bold: enable or disable bold mode.
  • dim: enable or disable dim mode. This is badly supported.
  • underline: enable or disable underline.
  • blink: enable or disable blinking.
  • reverse: enable or disable inverse rendering (foreground becomes background and the other way round).
  • reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.

Info

You can read more about it in Click's docs about style()

typer.secho() - style and print

There's a shorter form to style and print at the same time with typer.secho() it's like typer.echo() but also adds style like typer.style():

import typer


def main(name: str):
    typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)


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

Check it:

python main.py Camila Welcome here Camila