Contents

Typer library internals

0

This page is all about the typer python library, the contents below is auto-generated by inspecting a python package’s code base.

This page is experimental: if you are seeking help with the `typer` python package it's usually best to reference the libraries offical documentation page.

Package Files

  • typer/__init__.py
  • typer/_completion_click7.py
  • typer/_completion_click8.py
  • typer/_completion_shared.py
  • typer/colors.py
  • typer/completion.py
  • typer/core.py
  • typer/main.py
  • typer/models.py
  • typer/params.py
  • typer/py.typed
  • typer/testing.py
  • typer/utils.py

Package Classes

  • <class ‘click.exceptions.Abort’>
  • <class ‘click.exceptions.BadParameter’>
  • <class ’typer.models.CallbackParam'>
  • <class ’typer.models.Context'>
  • <class ‘click.exceptions.Exit’>
  • <class ’typer.models.FileBinaryRead'>
  • <class ’typer.models.FileBinaryWrite'>
  • <class ’typer.models.FileText'>
  • <class ’typer.models.FileTextWrite'>
  • <class ’typer.main.Typer'>

Package Methods

typer.Argument()

typer.Argument(default: Optional[Any], *, callback: Optional[Callable[..., Any]] = None, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Union[str, List[str], NoneType] = None, shell_complete: Optional[Callable[[click.core.Context, click.core.Parameter, str], Union[List[ForwardRef('click.shell_completion.CompletionItem')], List[str]]]] = None, autocompletion: Optional[Callable[..., Any]] = None, show_default: Union[bool, str] = True, show_choices: bool = True, show_envvar: bool = True, help: Optional[str] = None, hidden: bool = False, case_sensitive: bool = True, min: Union[int, float, NoneType] = None, max: Union[int, float, NoneType] = None, clamp: bool = False, formats: Optional[List[str]] = None, mode: Optional[str] = None, encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: Optional[bool] = None, atomic: bool = False, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Union[NoneType, Type[str], Type[bytes]] = None) -> Any

typer.Argument(
  default,
  callback,
  metavar,
  expose_value,
  is_eager,
  envvar,
  shell_complete,
  autocompletion,
  show_default,
  show_choices,
  show_envvar,
  help,
  hidden,
  case_sensitive,
  min,
  max,
  clamp,
  formats,
  mode,
  encoding,
  errors,
  lazy,
  atomic,
  exists,
  file_okay,
  dir_okay,
  writable,
  readable,
  resolve_path,
  allow_dash,
  path_type,
)

typer.Option()

typer.Option(default: Optional[Any], *param_decls: str, callback: Optional[Callable[..., Any]] = None, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Union[str, List[str], NoneType] = None, shell_complete: Optional[Callable[[click.core.Context, click.core.Parameter, str], Union[List[ForwardRef('click.shell_completion.CompletionItem')], List[str]]]] = None, autocompletion: Optional[Callable[..., Any]] = None, show_default: bool = True, prompt: Union[bool, str] = False, confirmation_prompt: bool = False, prompt_required: bool = True, hide_input: bool = False, is_flag: Optional[bool] = None, flag_value: Optional[Any] = None, count: bool = False, allow_from_autoenv: bool = True, help: Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = True, case_sensitive: bool = True, min: Union[int, float, NoneType] = None, max: Union[int, float, NoneType] = None, clamp: bool = False, formats: Optional[List[str]] = None, mode: Optional[str] = None, encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: Optional[bool] = None, atomic: bool = False, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Union[NoneType, Type[str], Type[bytes]] = None) -> Any

typer.Option(
  default,
  param_decls,
  callback,
  metavar,
  expose_value,
  is_eager,
  envvar,
  shell_complete,
  autocompletion,
  show_default,
  prompt,
  confirmation_prompt,
  prompt_required,
  hide_input,
  is_flag,
  flag_value,
  count,
  allow_from_autoenv,
  help,
  hidden,
  show_choices,
  show_envvar,
  case_sensitive,
  min,
  max,
  clamp,
  formats,
  mode,
  encoding,
  errors,
  lazy,
  atomic,
  exists,
  file_okay,
  dir_okay,
  writable,
  readable,
  resolve_path,
  allow_dash,
  path_type,
)

typer.clear()

the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.

.. versionadded:: 2.0

typer.clear() -> None

typer.clear(
)

typer.confirm()

If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:Abort exception.

typer.confirm(text: str, default: Optional[bool] = False, abort: bool = False, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False) -> bool

typer.confirm(
  text,
  default,
  abort,
  prompt_suffix,
  show_default,
  err,
)

typer.echo()

used instead of :func:print because it provides better support for different data, files, and environments.

Compared to :func:print, this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.
  • Supports Unicode in the Windows console.
  • Supports writing to binary outputs, and supports writing bytes to text outputs.
  • Supports colors and styles on Windows.
  • Removes ANSI color and style codes if the output does not look like an interactive terminal.
  • Always flushes the output.
typer.echo(message: Optional[Any] = None, file: Optional[IO] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None) -> None

typer.echo(
  message,
  file,
  nl,
  err,
  color,
)

typer.echo_via_pager()

pager on stdout.

.. versionchanged:: 3.0 Added the color flag.

typer.echo_via_pager(text_or_generator: Union[Iterable[str], Callable[[], Iterable[str]], str], color: Optional[bool] = None) -> None

typer.echo_via_pager(
  text_or_generator,
  color,
)

typer.edit()

(should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.

If the editor cannot be opened a :exc:UsageError is raised.

Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have \n as newline markers.

typer.edit(text: Optional[~AnyStr] = None, editor: Optional[str] = None, env: Optional[Mapping[str, str]] = None, require_save: bool = True, extension: str = '.txt', filename: Optional[str] = None) -> Optional[~AnyStr]

typer.edit(
  text,
  editor,
  env,
  require_save,
  extension,
  filename,
)

typer.format_filename()

function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename.

typer.format_filename(filename: Union[str, bytes, os.PathLike], shorten: bool = False) -> str

typer.format_filename(
  filename,
  shorten,
)

typer.get_app_dir()

is to return whatever is most appropriate for the operating system.

To give you an idea, for an app called "Foo Bar", something like the following folders could be returned:

Mac OS X: ~/Library/Application Support/Foo Bar Mac OS X (POSIX): ~/.foo-bar Unix: ~/.config/foo-bar Unix (POSIX): ~/.foo-bar Windows (roaming): C:\Users\<user>\AppData\Roaming\Foo Bar Windows (not roaming): C:\Users\<user>\AppData\Local\Foo Bar

.. versionadded:: 2.0

typer.get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str

typer.get_app_dir(
  app_name,
  roaming,
  force_posix,
)

typer.get_binary_stream()

typer.get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> <class 'BinaryIO'>

typer.get_binary_stream(
  name,
)

typer.get_terminal_size()

(width, height) in columns and rows.

typer.get_terminal_size() -> os.terminal_size

typer.get_terminal_size(
)

typer.get_text_stream()

a wrapped stream around a binary stream returned from

typer.get_text_stream(name: "te.Literal['stdin', 'stdout', 'stderr']", encoding: Optional[str] = None, errors: Optional[str] = 'strict') -> <class 'TextIO'>

typer.get_text_stream(
  name,
  encoding,
  errors,
)

typer.getchar()

will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.

Note that this will always read from the terminal, even if something is piped into the standard input.

Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.

.. versionadded:: 2.0

typer.getchar(echo: bool = False) -> str

typer.getchar(
  echo,
)

typer.launch()

viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, 0 indicates success.

Examples::

click.launch('https://click.palletsprojects.com/')
click.launch('/my/downloaded/file', locate=True)

.. versionadded:: 2.0

typer.launch(url: str, wait: bool = False, locate: bool = False) -> int

typer.launch(
  url,
  wait,
  locate,
)

typer.open_file()

usage. Files are opened non lazy by default. This can open regular files as well as stdin/stdout if '-' is passed.

If stdin/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream::

with open_file(filename) as f:
    ...

.. versionadded:: 3.0

typer.open_file(filename: str, mode: str = 'r', encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: bool = False, atomic: bool = False) -> <class 'IO'>

typer.open_file(
  filename,
  mode,
  encoding,
  errors,
  lazy,
  atomic,
)

typer.pause()

key to continue. This is similar to the Windows batch “pause” command. If the program is not run through a terminal, this command will instead do nothing.

.. versionadded:: 2.0

.. versionadded:: 4.0 Added the err parameter.

typer.pause(info: Optional[str] = None, err: bool = False) -> None

typer.pause(
  info,
  err,
)

typer.progressbar()

to iterate over something while showing a progress bar. It will either iterate over the iterable or length items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given file (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.

The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.

Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won’t display progress that is considered too fast, and progress where the time between steps is less than a second.

No printing must happen or the progress bar will be unintentionally destroyed.

Example usage::

with progressbar(items) as bar:
    for item in bar:
        do_something_with(item)

Alternatively, if no iterable is specified, one can manually update the progress bar through the update() method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with::

with progressbar(length=chunks.total_bytes) as bar:
    for chunk in chunks:
        process_chunk(chunk)
        bar.update(chunks.bytes)

The update() method also takes an optional value specifying the current_item at the new position. This is useful when used together with item_show_func to customize the output for each manual step::

with click.progressbar(
    length=total_size,
    label='Unzipping archive',
    item_show_func=lambda a: a.filename
) as bar:
    for archive in zip_file:
        archive.extract()
        bar.update(archive.size, archive)
typer.progressbar(iterable: Optional[Iterable[~V]] = None, length: Optional[int] = None, label: Optional[str] = None, show_eta: bool = True, show_percent: Optional[bool] = None, show_pos: bool = False, item_show_func: Optional[Callable[[Optional[~V]], Optional[str]]] = None, fill_char: str = '#', empty_char: str = '-', bar_template: str = '%(label)s  [%(bar)s]  %(info)s', info_sep: str = '  ', width: int = 36, file: Optional[TextIO] = None, color: Optional[bool] = None, update_min_steps: int = 1) -> 'ProgressBar[V]'

typer.progressbar(
  iterable,
  length,
  label,
  show_eta,
  show_percent,
  show_pos,
  item_show_func,
  fill_char,
  empty_char,
  bar_template,
  info_sep,
  width,
  file,
  color,
  update_min_steps,
)

typer.prompt()

be used to prompt a user for input later.

If the user aborts the input by sending a interrupt signal, this function will catch it and raise a :exc:Abort exception.

typer.prompt(text: str, default: Optional[Any] = None, hide_input: bool = False, confirmation_prompt: Union[bool, str] = False, type: Union[click.types.ParamType, Any, NoneType] = None, value_proc: Optional[Callable[[str], Any]] = None, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False, show_choices: bool = True) -> Any

typer.prompt(
  text,
  default,
  hide_input,
  confirmation_prompt,
  type,
  value_proc,
  prompt_suffix,
  show_default,
  err,
  show_choices,
)

typer.run()

typer.run(function: Callable[..., Any]) -> Any

typer.run(
  function,
)

typer.secho()

call. As such the following two calls are the same::

click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))

All keyword arguments are forwarded to the underlying functions depending on which one they go with.

Non-string types will be converted to :class:str. However,

typer.secho(message: Optional[Any] = None, file: Optional[IO] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None, **styles: Any) -> None

typer.secho(
  message,
  file,
  nl,
  err,
  color,
  styles,
)

typer.style()

default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset=False.

Examples::

click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))

Supported color names:

  • black (might be a gray)
  • red
  • green
  • yellow (might be an orange)
  • blue
  • magenta
  • cyan
  • white (might be light gray)
  • bright_black
  • bright_red
  • bright_green
  • bright_yellow
  • bright_blue
  • bright_magenta
  • bright_cyan
  • bright_white
  • reset (reset the color code only)

If the terminal supports it, color may also be specified as:

  • An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode.
  • An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.

See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.

typer.style(text: Any, fg: Union[int, Tuple[int, int, int], str, NoneType] = None, bg: Union[int, Tuple[int, int, int], str, NoneType] = None, bold: Optional[bool] = None, dim: Optional[bool] = None, underline: Optional[bool] = None, overline: Optional[bool] = None, italic: Optional[bool] = None, blink: Optional[bool] = None, reverse: Optional[bool] = None, strikethrough: Optional[bool] = None, reset: bool = True) -> str

typer.style(
  text,
  fg,
  bg,
  bold,
  dim,
  underline,
  overline,
  italic,
  blink,
  reverse,
  strikethrough,
  reset,
)

typer.unstyle()

necessary to use this function as Click’s echo function will automatically remove styling if necessary.

.. versionadded:: 2.0

typer.unstyle(text: str) -> str

typer.unstyle(
  text,
)