Skip to content

Context

Every app has a special internal object that keeps track of state relevant to the script's execution. For some advanced use-cases, you may want to access it directly. This can be done by declaring a function parameter of type typer.Context.

Similarly, you can also declare a function parameter with type typer.CallbackParam in case a callback could be used by several CLI parameters, and you need to figure out which one it was.

from typing import Annotated

import typer

app = typer.Typer()


def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):
    if ctx.resilient_parsing:
        return
    print(f"Validating param: {param.name}")
    if value != "Rick":
        raise typer.BadParameter("Only Rick is allowed")
    return value


@app.command()
def main(name: Annotated[str | None, typer.Option(callback=name_callback)] = None):
    print(f"Hello {name}")


if __name__ == "__main__":
    app()

typer.Context

Context(
    command,
    parent=None,
    info_name=None,
    obj=None,
    auto_envvar_prefix=None,
    default_map=None,
    terminal_width=None,
    max_content_width=None,
    resilient_parsing=False,
    allow_extra_args=None,
    allow_interspersed_args=None,
    ignore_unknown_options=None,
    help_option_names=None,
    token_normalize_func=None,
    color=None,
    show_default=None,
)

Bases: Context

The Context has some additional data about the current execution of your program. When declaring it in a callback function, you can access this additional information.

Source code in typer/_click/core.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def __init__(
    self,
    command: Command,
    parent: Context | None = None,
    info_name: str | None = None,
    obj: t.Any | None = None,
    auto_envvar_prefix: str | None = None,
    default_map: cabc.MutableMapping[str, t.Any] | None = None,
    terminal_width: int | None = None,
    max_content_width: int | None = None,
    resilient_parsing: bool = False,
    allow_extra_args: bool | None = None,
    allow_interspersed_args: bool | None = None,
    ignore_unknown_options: bool | None = None,
    help_option_names: list[str] | None = None,
    token_normalize_func: t.Callable[[str], str] | None = None,
    color: bool | None = None,
    show_default: bool | None = None,
) -> None:
    #: the parent context or `None` if none exists.
    self.parent = parent
    #: the :class:`Command` for this context.
    self.command = command
    #: the descriptive information name
    self.info_name = info_name
    #: Map of parameter names to their parsed values. Parameters
    #: with ``expose_value=False`` are not stored.
    self.params: dict[str, t.Any] = {}
    #: the leftover arguments.
    self.args: list[str] = []
    #: protected arguments.  These are arguments that are prepended
    #: to `args` when certain parsing scenarios are encountered but
    #: must be never propagated to another arguments.  This is used
    #: to implement nested parsing.
    self._protected_args: list[str] = []
    #: the collected prefixes of the command's options.
    self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()

    if obj is None and parent is not None:
        obj = parent.obj

    #: the user object stored.
    self.obj: t.Any = obj
    self._meta: dict[str, t.Any] = getattr(parent, "meta", {})

    #: A dictionary (-like object) with defaults for parameters.
    if (
        default_map is None
        and info_name is not None
        and parent is not None
        and parent.default_map is not None
    ):
        default_map = parent.default_map.get(info_name)

    self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map

    #: This flag indicates if a subcommand is going to be executed. A
    #: group callback can use this information to figure out if it's
    #: being executed directly or because the execution flow passes
    #: onwards to a subcommand. By default it's None, but it can be
    #: the name of the subcommand to execute.
    #:
    #: If chaining is enabled this will be set to ``'*'`` in case
    #: any commands are executed.  It is however not possible to
    #: figure out which ones.  If you require this knowledge you
    #: should use a :func:`result_callback`.
    self.invoked_subcommand: str | None = None

    if terminal_width is None and parent is not None:
        terminal_width = parent.terminal_width

    #: The width of the terminal (None is autodetection).
    self.terminal_width: int | None = terminal_width

    if max_content_width is None and parent is not None:
        max_content_width = parent.max_content_width

    #: The maximum width of formatted content (None implies a sensible
    #: default which is 80 for most things).
    self.max_content_width: int | None = max_content_width

    if allow_extra_args is None:
        allow_extra_args = command.allow_extra_args

    #: Indicates if the context allows extra args or if it should
    #: fail on parsing.
    #:
    #: .. versionadded:: 3.0
    self.allow_extra_args = allow_extra_args

    if allow_interspersed_args is None:
        allow_interspersed_args = command.allow_interspersed_args

    #: Indicates if the context allows mixing of arguments and
    #: options or not.
    #:
    #: .. versionadded:: 3.0
    self.allow_interspersed_args: bool = allow_interspersed_args

    if ignore_unknown_options is None:
        ignore_unknown_options = command.ignore_unknown_options

    #: Instructs click to ignore options that a command does not
    #: understand and will store it on the context for later
    #: processing.  This is primarily useful for situations where you
    #: want to call into external programs.  Generally this pattern is
    #: strongly discouraged because it's not possibly to losslessly
    #: forward all arguments.
    #:
    #: .. versionadded:: 4.0
    self.ignore_unknown_options: bool = ignore_unknown_options

    if help_option_names is None:
        if parent is not None:
            help_option_names = parent.help_option_names
        else:
            help_option_names = ["--help"]

    #: The names for the help options.
    self.help_option_names: list[str] = help_option_names

    if token_normalize_func is None and parent is not None:
        token_normalize_func = parent.token_normalize_func

    #: An optional normalization function for tokens.  This is
    #: options, choices, commands etc.
    self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func

    #: Indicates if resilient parsing is enabled.  In that case Click
    #: will do its best to not cause any failures and default values
    #: will be ignored. Useful for completion.
    self.resilient_parsing: bool = resilient_parsing

    # If there is no envvar prefix yet, but the parent has one and
    # the command on this level has a name, we can expand the envvar
    # prefix automatically.
    if auto_envvar_prefix is None:
        if (
            parent is not None
            and parent.auto_envvar_prefix is not None
            and self.info_name is not None
        ):
            auto_envvar_prefix = (
                f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
            )
    else:
        auto_envvar_prefix = auto_envvar_prefix.upper()

    if auto_envvar_prefix is not None:
        auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")

    self.auto_envvar_prefix: str | None = auto_envvar_prefix

    if color is None and parent is not None:
        color = parent.color

    #: Controls if styling output is wanted or not.
    self.color: bool | None = color

    if show_default is None and parent is not None:
        show_default = parent.show_default

    #: Show option default values when formatting help text.
    self.show_default: bool | None = show_default

    self._close_callbacks: list[t.Callable[[], t.Any]] = []
    self._depth = 0
    self._parameter_source: dict[str, ParameterSource] = {}
    self._exit_stack = ExitStack()

formatter_class class-attribute instance-attribute

formatter_class = HelpFormatter

parent instance-attribute

parent = parent

command instance-attribute

command = command

info_name instance-attribute

info_name = info_name

params instance-attribute

params = {}

args instance-attribute

args = []

obj instance-attribute

obj = obj

default_map instance-attribute

default_map = default_map

invoked_subcommand instance-attribute

invoked_subcommand = None

terminal_width instance-attribute

terminal_width = terminal_width

max_content_width instance-attribute

max_content_width = max_content_width

allow_extra_args instance-attribute

allow_extra_args = allow_extra_args

allow_interspersed_args instance-attribute

allow_interspersed_args = allow_interspersed_args

ignore_unknown_options instance-attribute

ignore_unknown_options = ignore_unknown_options

help_option_names instance-attribute

help_option_names = help_option_names

token_normalize_func instance-attribute

token_normalize_func = token_normalize_func

resilient_parsing instance-attribute

resilient_parsing = resilient_parsing

auto_envvar_prefix instance-attribute

auto_envvar_prefix = auto_envvar_prefix

color instance-attribute

color = color

show_default instance-attribute

show_default = show_default

protected_args property

protected_args

meta property

meta

This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well.

The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system.

Example usage::

LANG_KEY = f'{__name__}.lang'

def set_language(value):
    ctx = get_current_context()
    ctx.meta[LANG_KEY] = value

def get_language():
    return get_current_context().meta.get(LANG_KEY, 'en_US')

.. versionadded:: 5.0

command_path property

command_path

The computed command path. This is used for the usage information on the help page. It's automatically created by combining the info names of the chain of contexts to the root.

scope

scope(cleanup=True)

This helper method can be used with the context object to promote it to the current thread local (see :func:get_current_context). The default behavior of this is to invoke the cleanup functions which can be disabled by setting cleanup to False. The cleanup functions are typically used for things such as closing file handles.

If the cleanup is intended the context object can also be directly used as a context manager.

Example usage::

with ctx.scope():
    assert get_current_context() is ctx

This is equivalent::

with ctx:
    assert get_current_context() is ctx

.. versionadded:: 5.0

:param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup.

Source code in typer/_click/core.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
@contextmanager
def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
    """This helper method can be used with the context object to promote
    it to the current thread local (see :func:`get_current_context`).
    The default behavior of this is to invoke the cleanup functions which
    can be disabled by setting `cleanup` to `False`.  The cleanup
    functions are typically used for things such as closing file handles.

    If the cleanup is intended the context object can also be directly
    used as a context manager.

    Example usage::

        with ctx.scope():
            assert get_current_context() is ctx

    This is equivalent::

        with ctx:
            assert get_current_context() is ctx

    .. versionadded:: 5.0

    :param cleanup: controls if the cleanup functions should be run or
                    not.  The default is to run these functions.  In
                    some situations the context only wants to be
                    temporarily pushed in which case this can be disabled.
                    Nested pushes automatically defer the cleanup.
    """
    if not cleanup:
        self._depth += 1
    try:
        with self as rv:
            yield rv
    finally:
        if not cleanup:
            self._depth -= 1

make_formatter

make_formatter()

Creates the :class:~click.HelpFormatter for the help and usage output.

To quickly customize the formatter class used without overriding this method, set the :attr:formatter_class attribute.

.. versionchanged:: 8.0 Added the :attr:formatter_class attribute.

Source code in typer/_click/core.py
515
516
517
518
519
520
521
522
523
524
525
526
527
def make_formatter(self) -> HelpFormatter:
    """Creates the :class:`~click.HelpFormatter` for the help and
    usage output.

    To quickly customize the formatter class used without overriding
    this method, set the :attr:`formatter_class` attribute.

    .. versionchanged:: 8.0
        Added the :attr:`formatter_class` attribute.
    """
    return self.formatter_class(
        width=self.terminal_width, max_width=self.max_content_width
    )

with_resource

with_resource(context_manager)

Register a resource as if it were used in a with statement. The resource will be cleaned up when the context is popped.

Uses :meth:contextlib.ExitStack.enter_context. It calls the resource's __enter__() method and returns the result. When the context is popped, it closes the stack, which calls the resource's __exit__() method.

To register a cleanup function for something that isn't a context manager, use :meth:call_on_close. Or use something from :mod:contextlib to turn it into a context manager first.

.. code-block:: python

@click.group()
@click.option("--name")
@click.pass_context
def cli(ctx):
    ctx.obj = ctx.with_resource(connect_db(name))

:param context_manager: The context manager to enter. :return: Whatever context_manager.__enter__() returns.

.. versionadded:: 8.0

Source code in typer/_click/core.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
    """Register a resource as if it were used in a ``with``
    statement. The resource will be cleaned up when the context is
    popped.

    Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
    resource's ``__enter__()`` method and returns the result. When
    the context is popped, it closes the stack, which calls the
    resource's ``__exit__()`` method.

    To register a cleanup function for something that isn't a
    context manager, use :meth:`call_on_close`. Or use something
    from :mod:`contextlib` to turn it into a context manager first.

    .. code-block:: python

        @click.group()
        @click.option("--name")
        @click.pass_context
        def cli(ctx):
            ctx.obj = ctx.with_resource(connect_db(name))

    :param context_manager: The context manager to enter.
    :return: Whatever ``context_manager.__enter__()`` returns.

    .. versionadded:: 8.0
    """
    return self._exit_stack.enter_context(context_manager)

call_on_close

call_on_close(f)

Register a function to be called when the context tears down.

This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a with statement should be registered with :meth:with_resource instead.

:param f: The function to execute on teardown.

Source code in typer/_click/core.py
558
559
560
561
562
563
564
565
566
567
568
def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
    """Register a function to be called when the context tears down.

    This can be used to close resources opened during the script
    execution. Resources that support Python's context manager
    protocol which would be used in a ``with`` statement should be
    registered with :meth:`with_resource` instead.

    :param f: The function to execute on teardown.
    """
    return self._exit_stack.callback(f)

close

close()

Invoke all close callbacks registered with :meth:call_on_close, and exit all context managers entered with :meth:with_resource.

Source code in typer/_click/core.py
570
571
572
573
574
575
def close(self) -> None:
    """Invoke all close callbacks registered with
    :meth:`call_on_close`, and exit all context managers entered
    with :meth:`with_resource`.
    """
    self._close_with_exception_info(None, None, None)

find_root

find_root()

Finds the outermost context.

Source code in typer/_click/core.py
614
615
616
617
618
619
def find_root(self) -> Context:
    """Finds the outermost context."""
    node = self
    while node.parent is not None:
        node = node.parent
    return node

find_object

find_object(object_type)

Finds the closest object of a given type.

Source code in typer/_click/core.py
621
622
623
624
625
626
627
628
629
630
631
def find_object(self, object_type: type[V]) -> V | None:
    """Finds the closest object of a given type."""
    node: Context | None = self

    while node is not None:
        if isinstance(node.obj, object_type):
            return node.obj

        node = node.parent

    return None

ensure_object

ensure_object(object_type)

Like :meth:find_object but sets the innermost object to a new instance of object_type if it does not exist.

Source code in typer/_click/core.py
633
634
635
636
637
638
639
640
def ensure_object(self, object_type: type[V]) -> V:
    """Like :meth:`find_object` but sets the innermost object to a
    new instance of `object_type` if it does not exist.
    """
    rv = self.find_object(object_type)
    if rv is None:
        self.obj = rv = object_type()
    return rv

lookup_default

lookup_default(
    name: str, call: Literal[True] = True
) -> Any | None
lookup_default(
    name: str, call: Literal[False] = ...
) -> Any | Callable[[], Any] | None
lookup_default(name, call=True)

Get the default for a parameter from :attr:default_map.

:param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead.

.. versionchanged:: 8.0 Added the call parameter.

Source code in typer/_click/core.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
    """Get the default for a parameter from :attr:`default_map`.

    :param name: Name of the parameter.
    :param call: If the default is a callable, call it. Disable to
        return the callable instead.

    .. versionchanged:: 8.0
        Added the ``call`` parameter.
    """
    if self.default_map is not None:
        value = self.default_map.get(name, UNSET)

        if call and callable(value):
            return value()

        return value

    return UNSET

fail

fail(message)

Aborts the execution of the program with a specific error message.

:param message: the error message to fail with.

Source code in typer/_click/core.py
672
673
674
675
676
677
678
def fail(self, message: str) -> t.NoReturn:
    """Aborts the execution of the program with a specific error
    message.

    :param message: the error message to fail with.
    """
    raise UsageError(message, self)

abort

abort()

Aborts the script.

Source code in typer/_click/core.py
680
681
682
def abort(self) -> t.NoReturn:
    """Aborts the script."""
    raise Abort()

exit

exit(code=0)

Exits the application with a given exit code.

.. versionchanged:: 8.2 Callbacks and context managers registered with :meth:call_on_close and :meth:with_resource are closed before exiting.

Source code in typer/_click/core.py
684
685
686
687
688
689
690
691
692
def exit(self, code: int = 0) -> t.NoReturn:
    """Exits the application with a given exit code.

    .. versionchanged:: 8.2
        Callbacks and context managers registered with :meth:`call_on_close`
        and :meth:`with_resource` are closed before exiting.
    """
    self.close()
    raise Exit(code)

get_usage

get_usage()

Helper method to get formatted usage string for the current context and command.

Source code in typer/_click/core.py
694
695
696
697
698
def get_usage(self) -> str:
    """Helper method to get formatted usage string for the current
    context and command.
    """
    return self.command.get_usage(self)

get_help

get_help()

Helper method to get formatted help page for the current context and command.

Source code in typer/_click/core.py
700
701
702
703
704
def get_help(self) -> str:
    """Helper method to get formatted help page for the current
    context and command.
    """
    return self.command.get_help(self)

invoke

invoke(
    callback: Callable[..., V],
    /,
    *args: Any,
    **kwargs: Any,
) -> V
invoke(
    callback: Command, /, *args: Any, **kwargs: Any
) -> Any
invoke(callback, /, *args, **kwargs)

Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:

  1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function.
  2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults.

.. versionchanged:: 8.0 All kwargs are tracked in :attr:params so they will be passed if :meth:forward is called at multiple levels.

.. versionchanged:: 3.2 A new context is created, and missing arguments use default values.

Source code in typer/_click/core.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def invoke(
    self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
) -> t.Any | V:
    """Invokes a command callback in exactly the way it expects.  There
    are two ways to invoke this method:

    1.  the first argument can be a callback and all other arguments and
        keyword arguments are forwarded directly to the function.
    2.  the first argument is a click command object.  In that case all
        arguments are forwarded as well but proper click parameters
        (options and click arguments) must be keyword arguments and Click
        will fill in defaults.

    .. versionchanged:: 8.0
        All ``kwargs`` are tracked in :attr:`params` so they will be
        passed if :meth:`forward` is called at multiple levels.

    .. versionchanged:: 3.2
        A new context is created, and missing arguments use default values.
    """
    if isinstance(callback, Command):
        other_cmd = callback

        if other_cmd.callback is None:
            raise TypeError(
                "The given command does not have a callback that can be invoked."
            )
        else:
            callback = t.cast("t.Callable[..., V]", other_cmd.callback)

        ctx = self._make_sub_context(other_cmd)

        for param in other_cmd.params:
            if param.name not in kwargs and param.expose_value:
                default_value = param.get_default(ctx)
                # We explicitly hide the :attr:`UNSET` value to the user, as we
                # choose to make it an implementation detail. And because ``invoke``
                # has been designed as part of Click public API, we return ``None``
                # instead. Refs:
                # https://github.com/pallets/click/issues/3066
                # https://github.com/pallets/click/issues/3065
                # https://github.com/pallets/click/pull/3068
                if default_value is UNSET:
                    default_value = None
                kwargs[param.name] = param.type_cast_value(  # type: ignore
                    ctx, default_value
                )

        # Track all kwargs as params, so that forward() will pass
        # them on in subsequent calls.
        ctx.params.update(kwargs)
    else:
        ctx = self

    with augment_usage_errors(self):
        with ctx:
            return callback(*args, **kwargs)

forward

forward(cmd, /, *args, **kwargs)

Similar to :meth:invoke but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.

.. versionchanged:: 8.0 All kwargs are tracked in :attr:params so they will be passed if forward is called at multiple levels.

Source code in typer/_click/core.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
    """Similar to :meth:`invoke` but fills in default keyword
    arguments from the current context if the other command expects
    it.  This cannot invoke callbacks directly, only other commands.

    .. versionchanged:: 8.0
        All ``kwargs`` are tracked in :attr:`params` so they will be
        passed if ``forward`` is called at multiple levels.
    """
    # Can only forward to other commands, not direct callbacks.
    if not isinstance(cmd, Command):
        raise TypeError("Callback is not a command.")

    for param in self.params:
        if param not in kwargs:
            kwargs[param] = self.params[param]

    return self.invoke(cmd, *args, **kwargs)

set_parameter_source

set_parameter_source(name, source)

Set the source of a parameter. This indicates the location from which the value of the parameter was obtained.

:param name: The name of the parameter. :param source: A member of :class:~click.core.ParameterSource.

Source code in typer/_click/core.py
799
800
801
802
803
804
805
806
def set_parameter_source(self, name: str, source: ParameterSource) -> None:
    """Set the source of a parameter. This indicates the location
    from which the value of the parameter was obtained.

    :param name: The name of the parameter.
    :param source: A member of :class:`~click.core.ParameterSource`.
    """
    self._parameter_source[name] = source

get_parameter_source

get_parameter_source(name)

Get the source of a parameter. This indicates the location from which the value of the parameter was obtained.

This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be :attr:~click.core.ParameterSource.DEFAULT only if the value was actually taken from the default.

:param name: The name of the parameter. :rtype: ParameterSource

.. versionchanged:: 8.0 Returns None if the parameter was not provided from any source.

Source code in typer/_click/core.py
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
def get_parameter_source(self, name: str) -> ParameterSource | None:
    """Get the source of a parameter. This indicates the location
    from which the value of the parameter was obtained.

    This can be useful for determining when a user specified a value
    on the command line that is the same as the default value. It
    will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
    value was actually taken from the default.

    :param name: The name of the parameter.
    :rtype: ParameterSource

    .. versionchanged:: 8.0
        Returns ``None`` if the parameter was not provided from any
        source.
    """
    return self._parameter_source.get(name)

typer.CallbackParam

CallbackParam(
    param_decls=None,
    type=None,
    required=False,
    default=UNSET,
    callback=None,
    nargs=None,
    multiple=False,
    metavar=None,
    expose_value=True,
    is_eager=False,
    envvar=None,
    shell_complete=None,
    deprecated=False,
)

Bases: Parameter

In a callback function, you can declare a function parameter with type CallbackParam to access the specific Click Parameter object.

Source code in typer/_click/core.py
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
def __init__(
    self,
    param_decls: cabc.Sequence[str] | None = None,
    type: types.ParamType | t.Any | None = None,
    required: bool = False,
    # XXX The default historically embed two concepts:
    # - the declaration of a Parameter object carrying the default (handy to
    #   arbitrage the default value of coupled Parameters sharing the same
    #   self.name, like flag options),
    # - and the actual value of the default.
    # It is confusing and is the source of many issues discussed in:
    # https://github.com/pallets/click/pull/3030
    # In the future, we might think of splitting it in two, not unlike
    # Option.is_flag and Option.flag_value: we could have something like
    # Parameter.is_default and Parameter.default_value.
    default: t.Any | t.Callable[[], t.Any] | None = UNSET,
    callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
    nargs: int | None = None,
    multiple: bool = False,
    metavar: str | None = None,
    expose_value: bool = True,
    is_eager: bool = False,
    envvar: str | cabc.Sequence[str] | None = None,
    shell_complete: t.Callable[
        [Context, Parameter, str], list[CompletionItem] | list[str]
    ]
    | None = None,
    deprecated: bool | str = False,
) -> None:
    self.name: str | None
    self.opts: list[str]
    self.secondary_opts: list[str]
    self.name, self.opts, self.secondary_opts = self._parse_decls(
        param_decls or (), expose_value
    )
    self.type: types.ParamType = types.convert_type(type, default)

    # Default nargs to what the type tells us if we have that
    # information available.
    if nargs is None:
        if self.type.is_composite:
            nargs = self.type.arity
        else:
            nargs = 1

    self.required = required
    self.callback = callback
    self.nargs = nargs
    self.multiple = multiple
    self.expose_value = expose_value
    self.default: t.Any | t.Callable[[], t.Any] | None = default
    self.is_eager = is_eager
    self.metavar = metavar
    self.envvar = envvar
    self._custom_shell_complete = shell_complete
    self.deprecated = deprecated

    if __debug__:
        if self.type.is_composite and nargs != self.type.arity:
            raise ValueError(
                f"'nargs' must be {self.type.arity} (or None) for"
                f" type {self.type!r}, but it was {nargs}."
            )

        if required and deprecated:
            raise ValueError(
                f"The {self.param_type_name} '{self.human_readable_name}' "
                "is deprecated and still required. A deprecated "
                f"{self.param_type_name} cannot be required."
            )

param_type_name class-attribute instance-attribute

param_type_name = 'parameter'

name instance-attribute

name

opts instance-attribute

opts

secondary_opts instance-attribute

secondary_opts

type instance-attribute

type = convert_type(type, default)

required instance-attribute

required = required

callback instance-attribute

callback = callback

nargs instance-attribute

nargs = nargs

multiple instance-attribute

multiple = multiple

expose_value instance-attribute

expose_value = expose_value

default instance-attribute

default = default

is_eager instance-attribute

is_eager = is_eager

metavar instance-attribute

metavar = metavar

envvar instance-attribute

envvar = envvar

deprecated instance-attribute

deprecated = deprecated

human_readable_name property

human_readable_name

Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments.

make_metavar

make_metavar(ctx)
Source code in typer/_click/core.py
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
def make_metavar(self, ctx: Context) -> str:
    if self.metavar is not None:
        return self.metavar

    metavar = self.type.get_metavar(param=self, ctx=ctx)

    if metavar is None:
        metavar = self.type.name.upper()

    if self.nargs != 1:
        metavar += "..."

    return metavar

get_default

get_default(
    ctx: Context, call: Literal[True] = True
) -> Any | None
get_default(
    ctx: Context, call: bool = ...
) -> Any | Callable[[], Any] | None
get_default(ctx, call=True)

Get the default for the parameter. Tries :meth:Context.lookup_default first, then the local default.

:param ctx: Current context. :param call: If the default is a callable, call it. Disable to return the callable instead.

.. versionchanged:: 8.0.2 Type casting is no longer performed when getting a default.

.. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text.

.. versionchanged:: 8.0 Looks at ctx.default_map first.

.. versionchanged:: 8.0 Added the call parameter.

Source code in typer/_click/core.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
def get_default(
    self, ctx: Context, call: bool = True
) -> t.Any | t.Callable[[], t.Any] | None:
    """Get the default for the parameter. Tries
    :meth:`Context.lookup_default` first, then the local default.

    :param ctx: Current context.
    :param call: If the default is a callable, call it. Disable to
        return the callable instead.

    .. versionchanged:: 8.0.2
        Type casting is no longer performed when getting a default.

    .. versionchanged:: 8.0.1
        Type casting can fail in resilient parsing mode. Invalid
        defaults will not prevent showing help text.

    .. versionchanged:: 8.0
        Looks at ``ctx.default_map`` first.

    .. versionchanged:: 8.0
        Added the ``call`` parameter.
    """
    value = ctx.lookup_default(self.name, call=False)  # type: ignore

    if value is UNSET:
        value = self.default

    if call and callable(value):
        value = value()

    return value

add_to_parser

add_to_parser(parser, ctx)
Source code in typer/_click/core.py
2000
2001
def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
    raise NotImplementedError()

consume_value

consume_value(ctx, opts)

Returns the parameter value produced by the parser.

If the parser did not produce a value from user input, the value is either sourced from the environment variable, the default map, or the parameter's default value. In that order of precedence.

If no value is found, an internal sentinel value is returned.

:meta private:

Source code in typer/_click/core.py
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
def consume_value(
    self, ctx: Context, opts: cabc.Mapping[str, t.Any]
) -> tuple[t.Any, ParameterSource]:
    """Returns the parameter value produced by the parser.

    If the parser did not produce a value from user input, the value is either
    sourced from the environment variable, the default map, or the parameter's
    default value. In that order of precedence.

    If no value is found, an internal sentinel value is returned.

    :meta private:
    """
    # Collect from the parse the value passed by the user to the CLI.
    value = opts.get(self.name, UNSET)  # type: ignore
    # If the value is set, it means it was sourced from the command line by the
    # parser, otherwise it left unset by default.
    source = (
        ParameterSource.COMMANDLINE
        if value is not UNSET
        else ParameterSource.DEFAULT
    )

    if value is UNSET:
        envvar_value = self.value_from_envvar(ctx)
        if envvar_value is not None:
            value = envvar_value
            source = ParameterSource.ENVIRONMENT

    if value is UNSET:
        default_map_value = ctx.lookup_default(self.name)  # type: ignore
        if default_map_value is not UNSET:
            value = default_map_value
            source = ParameterSource.DEFAULT_MAP

    if value is UNSET:
        default_value = self.get_default(ctx)
        if default_value is not UNSET:
            value = default_value
            source = ParameterSource.DEFAULT

    return value, source

type_cast_value

type_cast_value(ctx, value)

Convert and validate a value against the parameter's :attr:type, :attr:multiple, and :attr:nargs.

Source code in typer/_click/core.py
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
    """Convert and validate a value against the parameter's
    :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
    """
    if value is None:
        if self.multiple or self.nargs == -1:
            return ()
        else:
            return value

    def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
        try:
            return _check_iter(value)
        except TypeError:
            # This should only happen when passing in args manually,
            # the parser should construct an iterable when parsing
            # the command line.
            raise BadParameter(
                _("Value must be an iterable."), ctx=ctx, param=self
            ) from None

    # Define the conversion function based on nargs and type.

    if self.nargs == 1 or self.type.is_composite:

        def convert(value: t.Any) -> t.Any:
            return self.type(value, param=self, ctx=ctx)

    elif self.nargs == -1:

        def convert(value: t.Any) -> t.Any:  # tuple[t.Any, ...]
            return tuple(self.type(x, self, ctx) for x in check_iter(value))

    else:  # nargs > 1

        def convert(value: t.Any) -> t.Any:  # tuple[t.Any, ...]
            value = tuple(check_iter(value))

            if len(value) != self.nargs:
                raise BadParameter(
                    ngettext(
                        "Takes {nargs} values but 1 was given.",
                        "Takes {nargs} values but {len} were given.",
                        len(value),
                    ).format(nargs=self.nargs, len=len(value)),
                    ctx=ctx,
                    param=self,
                )

            return tuple(self.type(x, self, ctx) for x in value)

    if self.multiple:
        return tuple(convert(x) for x in check_iter(value))

    return convert(value)

value_is_missing

value_is_missing(value)

A value is considered missing if:

  • it is :attr:UNSET,
  • or if it is an empty sequence while the parameter is suppose to have non-single value (i.e. :attr:nargs is not 1 or :attr:multiple is set).

:meta private:

Source code in typer/_click/core.py
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
def value_is_missing(self, value: t.Any) -> bool:
    """A value is considered missing if:

    - it is :attr:`UNSET`,
    - or if it is an empty sequence while the parameter is suppose to have
      non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is
      set).

    :meta private:
    """
    if value is UNSET:
        return True

    if (self.nargs != 1 or self.multiple) and value == ():
        return True

    return False

process_value

process_value(ctx, value)

Process the value of this parameter:

  1. Type cast the value using :meth:type_cast_value.
  2. Check if the value is missing (see: :meth:value_is_missing), and raise :exc:MissingParameter if it is required.
  3. If a :attr:callback is set, call it to have the value replaced by the result of the callback. If the value was not set, the callback receive None. This keep the legacy behavior as it was before the introduction of the :attr:UNSET sentinel.

:meta private:

Source code in typer/_click/core.py
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
def process_value(self, ctx: Context, value: t.Any) -> t.Any:
    """Process the value of this parameter:

    1. Type cast the value using :meth:`type_cast_value`.
    2. Check if the value is missing (see: :meth:`value_is_missing`), and raise
       :exc:`MissingParameter` if it is required.
    3. If a :attr:`callback` is set, call it to have the value replaced by the
       result of the callback. If the value was not set, the callback receive
       ``None``. This keep the legacy behavior as it was before the introduction of
       the :attr:`UNSET` sentinel.

    :meta private:
    """
    # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the
    # cases in which `UNSET` gets special treatment explicitly at this layer
    #
    # Refs:
    # https://github.com/pallets/click/issues/3069
    if value is UNSET:
        if self.multiple or self.nargs == -1:
            value = ()
    else:
        value = self.type_cast_value(ctx, value)

    if self.required and self.value_is_missing(value):
        raise MissingParameter(ctx=ctx, param=self)

    if self.callback is not None:
        # Legacy case: UNSET is not exposed directly to the callback, but converted
        # to None.
        if value is UNSET:
            value = None

        # Search for parameters with UNSET values in the context.
        unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET}
        # No UNSET values, call the callback as usual.
        if not unset_keys:
            value = self.callback(ctx, self, value)

        # Legacy case: provide a temporarily manipulated context to the callback
        # to hide UNSET values as None.
        #
        # Refs:
        # https://github.com/pallets/click/issues/3136
        # https://github.com/pallets/click/pull/3137
        else:
            # Add another layer to the context stack to clearly hint that the
            # context is temporarily modified.
            with ctx:
                # Update the context parameters to replace UNSET with None.
                ctx.params.update(unset_keys)
                # Feed these fake context parameters to the callback.
                value = self.callback(ctx, self, value)
                # Restore the UNSET values in the context parameters.
                ctx.params.update(
                    {
                        k: UNSET
                        for k in unset_keys
                        # Only restore keys that are present and still None, in case
                        # the callback modified other parameters.
                        if k in ctx.params and ctx.params[k] is None
                    }
                )

    return value

resolve_envvar_value

resolve_envvar_value(ctx)

Returns the value found in the environment variable(s) attached to this parameter.

Environment variables values are always returned as strings <https://docs.python.org/3/library/os.html#os.environ>_.

This method returns None if:

  • the :attr:envvar property is not set on the :class:Parameter,
  • the environment variable is not found in the environment,
  • the variable is found in the environment but its value is empty (i.e. the environment variable is present but has an empty string).

If :attr:envvar is setup with multiple environment variables, then only the first non-empty value is returned.

.. caution::

The raw value extracted from the environment is not normalized and is
returned as-is. Any normalization or reconciliation is performed later by
the :class:`Parameter`'s :attr:`type`.

:meta private:

Source code in typer/_click/core.py
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
def resolve_envvar_value(self, ctx: Context) -> str | None:
    """Returns the value found in the environment variable(s) attached to this
    parameter.

    Environment variables values are `always returned as strings
    <https://docs.python.org/3/library/os.html#os.environ>`_.

    This method returns ``None`` if:

    - the :attr:`envvar` property is not set on the :class:`Parameter`,
    - the environment variable is not found in the environment,
    - the variable is found in the environment but its value is empty (i.e. the
      environment variable is present but has an empty string).

    If :attr:`envvar` is setup with multiple environment variables,
    then only the first non-empty value is returned.

    .. caution::

        The raw value extracted from the environment is not normalized and is
        returned as-is. Any normalization or reconciliation is performed later by
        the :class:`Parameter`'s :attr:`type`.

    :meta private:
    """
    if not self.envvar:
        return None

    if isinstance(self.envvar, str):
        rv = os.environ.get(self.envvar)

        if rv:
            return rv
    else:
        for envvar in self.envvar:
            rv = os.environ.get(envvar)

            # Return the first non-empty value of the list of environment variables.
            if rv:
                return rv
            # Else, absence of value is interpreted as an environment variable that
            # is not set, so proceed to the next one.

    return None

value_from_envvar

value_from_envvar(ctx)

Process the raw environment variable string for this parameter.

Returns the string as-is or splits it into a sequence of strings if the parameter is expecting multiple values (i.e. its :attr:nargs property is set to a value other than 1).

:meta private:

Source code in typer/_click/core.py
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:
    """Process the raw environment variable string for this parameter.

    Returns the string as-is or splits it into a sequence of strings if the
    parameter is expecting multiple values (i.e. its :attr:`nargs` property is set
    to a value other than ``1``).

    :meta private:
    """
    rv = self.resolve_envvar_value(ctx)

    if rv is not None and self.nargs != 1:
        return self.type.split_envvar_value(rv)

    return rv

handle_parse_result

handle_parse_result(ctx, opts, args)

Process the value produced by the parser from user input.

Always process the value through the Parameter's :attr:type, wherever it comes from.

If the parameter is deprecated, this method warn the user about it. But only if the value has been explicitly set by the user (and as such, is not coming from a default).

:meta private:

Source code in typer/_click/core.py
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
def handle_parse_result(
    self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
) -> tuple[t.Any, list[str]]:
    """Process the value produced by the parser from user input.

    Always process the value through the Parameter's :attr:`type`, wherever it
    comes from.

    If the parameter is deprecated, this method warn the user about it. But only if
    the value has been explicitly set by the user (and as such, is not coming from
    a default).

    :meta private:
    """
    with augment_usage_errors(ctx, param=self):
        value, source = self.consume_value(ctx, opts)

        ctx.set_parameter_source(self.name, source)  # type: ignore

        # Display a deprecation warning if necessary.
        if (
            self.deprecated
            and value is not UNSET
            and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)
        ):
            extra_message = (
                f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
            )
            message = _(
                "DeprecationWarning: The {param_type} {name!r} is deprecated."
                "{extra_message}"
            ).format(
                param_type=self.param_type_name,
                name=self.human_readable_name,
                extra_message=extra_message,
            )
            echo(style(message, fg="red"), err=True)

        # Process the value through the parameter's type.
        try:
            value = self.process_value(ctx, value)
        except Exception:
            if not ctx.resilient_parsing:
                raise
            # In resilient parsing mode, we do not want to fail the command if the
            # value is incompatible with the parameter type, so we reset the value
            # to UNSET, which will be interpreted as a missing value.
            value = UNSET

    # Add parameter's value to the context.
    if (
        self.expose_value
        # We skip adding the value if it was previously set by another parameter
        # targeting the same variable name. This prevents parameters competing for
        # the same name to override each other.
        and (self.name not in ctx.params or ctx.params[self.name] is UNSET)
    ):
        # Click is logically enforcing that the name is None if the parameter is
        # not to be exposed. We still assert it here to please the type checker.
        assert self.name is not None, (
            f"{self!r} parameter's name should not be None when exposing value."
        )
        ctx.params[self.name] = value

    return value, args

get_help_record

get_help_record(ctx)
Source code in typer/_click/core.py
2313
2314
def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
    pass

get_usage_pieces

get_usage_pieces(ctx)
Source code in typer/_click/core.py
2316
2317
def get_usage_pieces(self, ctx: Context) -> list[str]:
    return []

get_error_hint

get_error_hint(ctx)

Get a stringified version of the param for use in error messages to indicate which param caused the error.

Source code in typer/_click/core.py
2319
2320
2321
2322
2323
2324
def get_error_hint(self, ctx: Context) -> str:
    """Get a stringified version of the param for use in error messages to
    indicate which param caused the error.
    """
    hint_list = self.opts or [self.human_readable_name]
    return " / ".join(f"'{x}'" for x in hint_list)

shell_complete

shell_complete(ctx, incomplete)

Return a list of completions for the incomplete value. If a shell_complete function was given during init, it is used. Otherwise, the :attr:type :meth:~click.types.ParamType.shell_complete function is used.

:param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty.

.. versionadded:: 8.0

Source code in typer/_click/core.py
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
    """Return a list of completions for the incomplete value. If a
    ``shell_complete`` function was given during init, it is used.
    Otherwise, the :attr:`type`
    :meth:`~click.types.ParamType.shell_complete` function is used.

    :param ctx: Invocation context for this command.
    :param incomplete: Value being completed. May be empty.

    .. versionadded:: 8.0
    """
    if self._custom_shell_complete is not None:
        results = self._custom_shell_complete(ctx, self, incomplete)

        if results and isinstance(results[0], str):
            from .shell_completion import CompletionItem

            results = [CompletionItem(c) for c in results]

        return t.cast("list[CompletionItem]", results)

    return self.type.shell_complete(ctx, self, incomplete)