Context¶
When you create a Typer application it uses Click underneath.
And every Click application has a special object called a Context that is normally hidden.
But you can access the context by declaring a function parameter of type typer.Context.
The same way you can access the context by declaring a function parameter with its value,
you can declare another function parameter with type typer.CallbackParam to get the specific Click Parameter object.
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
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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
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.
to_info_dict
¶
to_info_dict()
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure.
.. code-block:: python
with Context(cli) as ctx:
info = ctx.to_info_dict()
.. versionadded:: 8.0
Source code in typer/_click/core.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |
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
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
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
556 557 558 559 560 561 562 563 564 565 566 567 568 | |
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
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | |
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
599 600 601 602 603 604 605 606 607 608 609 | |
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
611 612 613 614 615 616 | |
find_root
¶
find_root()
Finds the outermost context.
Source code in typer/_click/core.py
655 656 657 658 659 660 | |
find_object
¶
find_object(object_type)
Finds the closest object of a given type.
Source code in typer/_click/core.py
662 663 664 665 666 667 668 669 670 671 672 | |
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
674 675 676 677 678 679 680 681 | |
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
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | |
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
713 714 715 716 717 718 719 | |
abort
¶
abort()
Aborts the script.
Source code in typer/_click/core.py
721 722 723 | |
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
725 726 727 728 729 730 731 732 733 | |
get_usage
¶
get_usage()
Helper method to get formatted usage string for the current context and command.
Source code in typer/_click/core.py
735 736 737 738 739 | |
get_help
¶
get_help()
Helper method to get formatted help page for the current context and command.
Source code in typer/_click/core.py
741 742 743 744 745 | |
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
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
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
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | |
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
840 841 842 843 844 845 846 847 | |
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
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 | |
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
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 2045 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 | |
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.
to_info_dict
¶
to_info_dict()
Gather information that could be useful for a tool generating user-facing documentation.
Use :meth:click.Context.to_info_dict to traverse the entire
CLI structure.
.. versionchanged:: 8.3.0
Returns None for the :attr:default if it was not set.
.. versionadded:: 8.0
Source code in typer/_click/core.py
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 | |
make_metavar
¶
make_metavar(ctx)
Source code in typer/_click/core.py
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 | |
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
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 | |
add_to_parser
¶
add_to_parser(parser, ctx)
Source code in typer/_click/core.py
2185 2186 | |
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
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 | |
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
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 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 | |
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
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 | |
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
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 | |
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
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 | |
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
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 | |
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
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 | |
get_help_record
¶
get_help_record(ctx)
Source code in typer/_click/core.py
2498 2499 | |
get_usage_pieces
¶
get_usage_pieces(ctx)
Source code in typer/_click/core.py
2501 2502 | |
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
2504 2505 2506 2507 2508 2509 | |
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
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 | |