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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
find_root
¶
find_root()
Finds the outermost context.
Source code in typer/_click/core.py
614 615 616 617 618 619 | |
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 | |
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 | |
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 | |
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 | |
abort
¶
abort()
Aborts the script.
Source code in typer/_click/core.py
680 681 682 | |
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 | |
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 | |
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 | |
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:
- the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function.
- 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
add_to_parser
¶
add_to_parser(parser, ctx)
Source code in typer/_click/core.py
2000 2001 | |
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 | |
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 | |
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:
nargsis not1or :attr:multipleis 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 | |
process_value
¶
process_value(ctx, value)
Process the value of this parameter:
- Type cast the value using :meth:
type_cast_value. - Check if the value is missing (see: :meth:
value_is_missing), and raise :exc:MissingParameterif it is required. - If a :attr:
callbackis set, call it to have the value replaced by the result of the callback. If the value was not set, the callback receiveNone. This keep the legacy behavior as it was before the introduction of the :attr:UNSETsentinel.
: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 | |
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:
envvarproperty 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 | |
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 | |
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 | |
get_help_record
¶
get_help_record(ctx)
Source code in typer/_click/core.py
2313 2314 | |
get_usage_pieces
¶
get_usage_pieces(ctx)
Source code in typer/_click/core.py
2316 2317 | |
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 | |
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 | |