Python Forum

Full Version: Help with passing value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here is my code,
#mycode.py
import click
import json

def read_config(ctx, param, value):
   d = json.load(value)

   #ctx.default_map = d

def retFunc(ctx, param, value):
   return value

@click.group(invoke_without_command = True)
@click.option('--config', callback=read_config, type=click.File('r'))
@click.option('--ret1', callback=retFunc)
@click.pass_context
def cli(ctx, **kwargs):
   pass

def main():
   cli()
   
if __name__ == '__main__':
   main()
The code above will read a json file called "config.json" shown below.
{
  "ret1" : 1
}
Now if I run "mycode.py" as mycode.py --config config.json, value won't be passed to the callback function retFunc. But I uncomment out the statement ctx.default_map = d in the callback function read_config, then I got the value passed to the function retFunc. Why? Thanks.
I wasn't able to figure this out quickly from the docs. If you've reviewed them carefully, and still aren't sure, I recommend you dig into their source and/or contact the author if the documentation is incorrect or incomplete.