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:
# test1.py
import click
@click.pass_context
def some_func(ctx, bar):
foo = ctx.params["foo"]
print(f"The value of foo is: {foo}")
@click.command()
@click.option("--foo")
@click.option("--bar")
def main(foo, bar):
some_func(bar)
if __name__ == "__main__":
main()
$ python test1.py --foo 1 --bar "bbb"
The value of foo is: 1
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).
# test2.py
import click
def some_func(bar):
c = click.get_current_context()
foo = c.params["foo"]
print(f"The value of foo is: {foo}")
@click.command()
@click.option("--foo")
@click.option("--bar")
def main(foo, bar):
some_func(bar)
if __name__ == "__main__":
main()
$ python test2.py --foo 1 --bar "bbb"
The value of foo is: 1