[Python] How to set a global click option that would be used as a base for different click...

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Python Click to develop a cli. I have the following situation:

    First I have a config file in config.py, where I store re-usable variables across my project

    # config.py

    class Config:
    base_path = "/home/project/"


    Then, I have a cli command in command.py, where I'm using the path config variable

    # command.py
    import click
    from config import Config

    @click.command()
    @click.option('--path', show_default=True, default=f"{Config.base_path}/some/another_path.json")
    def some_command(path):
    """ command example"""
    print(f"my path is: {path}")


    And finally, I have my parent cli or my entry point

    import click
    from config import Config
    from command import some_command

    @click.group()
    @click.option('--base-path', show_default=True, default=Config.base_path)
    @pass_context
    def cli(ctx, base_path):
    """ entry point"""
    ctx.obj = {"base_path": base_path}

    cli.add_command(some_command)


    So as you can see, I have a global config variable that I want users to be able to override through the cli

    For example, by running $ cli --base-path ~/custom/path some_command, I want the --path option for the some_command to be overridden to ~/custom/path/some/another_path.json as well since it is based on it.

    However, that is not what is happening because the --base-path would be overridden by the user at runtime and therefore the changes are not reflected. So my question is what is the best way to solve this problem?

    I tried to override the Config.base_path var like this:

    @click.group()
    @click.option('--base-path', show_default=True, default=Config.base_path)
    @pass_context
    def cli(ctx, base_path):
    """ entry point"""
    Config.base_path = base_path
    ctx.obj = {"base_path": base_path}


    Obviously that did not work because the variable was overridden in the context, which is after being set in the some_command command already.

    What can I try next?

    Continue reading...

Compartilhe esta Página