Skip to content
Myr

Documented the use of get_current_context

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 022fc73 · Browse files · 3 files+42 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+42 added−0 removed

  • other:+42 added−0 removed

3 files+42 added−0 removed

modified:docs/advanced.rst+39 added
336 unmodified lines
337your own commands and commands from another application are discouraged338and if you can avoid it, you should. It's a much better idea to have339everything below a subcommand be forwarded to another application than to340handle some arguments yourself.341342343Global Context Access344---------------------345346.. versionadded:: 5.0347348Starting with Click 5.0 it is possible to access the current context from349anywhere within the same through through the use of the350:func:`get_current_context` function which returns it. This is primarily351useful for accessing the context bound object as well as some flags that352are stored on it to customize the runtime behavior. For instance the353:func:`echo` function does this to infer the default value of the `color`354flag.355356Example usage::357358 def get_current_command_name():359 return click.get_current_context().info_name360361It should be noted that this only works within the current thread. If you362spawn additional threads then those threads will not have the ability to363refer to the current context. If you want to give another thread the364ability to refer to this context you need to use the context within the365thread as a context manager::366367 def spawn_thread(ctx, func):368 def wrapper():369 with ctx:370 func()371 t = threading.Thread(target=wrapper)372 t.start()373 return t374375Now the thread function can access the context like the main thread would376do. However if you do use this for threading you need to be very careful377as the vast majority of the context is not thread safe! You are only378allowed to read from the context, but not to perform any modifications on379it.
modified:docs/api.rst+2 added
104 unmodified lines
105106.. autoclass:: Context107 :members:108109.. autofunction:: get_current_context110111Types112-----113114.. autodata:: STRING
65 unmodified lines
modified:CHANGES+1 added
12 unmodified lines
13- Change the usage part of help output for very long commands to wrap14 their arguments onto the next line, indented by 4 spaces.15- Fix a bug where return code and error messages were incorrect when16 using ``CliRunner``.17- added `get_current_context`.1819Version 4.120-----------21
221 unmodified lines