Say I have an flag --debug/--no-debug
defined for the base command. This flag will affect the behavior of many operations in my program. Right now I find myself passing this flag as function parameters all over the place, which doesn't seem elegant. Especially when I need to access this flag in a deep call stack, I'll have to add this parameter to every single function on the stack.
I can instead create a global variable is_debug
and set its value at the beginning of the command function that receives the value of this flag. But this doesn't seem elegant to me either.
Is there a better way to make some option values globally accessible using the Click library?
There are two ways to do so, depending on your needs. Both of them end up using the click Context.
Personally, I'm a fan of Option 2 because then I don't have to modify function signatures (and I rarely write multi-threaded programs). It also sounds more like what you're looking for.
Option 1: Pass the Context to the function
Use the
click.pass_context
decorator to pass the click context to the function.Docs:
Option 2:
click.get_current_context()
Pull the context directly from the current thread via
click.get_current_context()
. Available starting in Click 5.0.Docs:
Note: This only works if you're in the current thread (the same thread as what was used to set up the click commands originally).