I'm trying to pass contexts between two subcommands with python-click. Here's an MWE:
import click
@click.group(chain=True)
def cli() -> None:
pass
@cli.command()
@click.pass_context
def fn1(cxt):
cxt.obj = 1
@cli.command()
@click.pass_context
def fn2(cxt):
print(f'{cxt.obj=}')
if __name__ == '__main__':
cli()
If I call this with cli.py fn1 fn2, I expect to get "cxt.obj=1", whereas I get "cxt.obj=None".
While trying to debug, I also noticed I can access the cli's context from fn1 and fn2, but not fn1's context from fn2. I can therefore, set the object of cli's context in fn1, and read from cli's context in fn2, but there must be a better way, where the obj is directly accessible in fn2's context.
What is wrong with my mental model, why doesn't the context persist between subcommands? And, what is the best pattern to use when one needs to pass data between subcommands?