Tuesday 28 December 2021

How to fix mypy error when using click's pass_context

I am using click to build a command line application. I am using mypy for type checking.

However, passing a context to a function using @pass_context works as expected, but mypy fails with the error:

error: Argument 1 to "print_or_exit" has incompatible type "str"; expected "Context"

and I don't get why. Below is the MWE to reproduce this mypy error:

import click
from typing import Optional

@click.pass_context
def print_or_exit(ctx: click.Context, some_txt: Optional[str] = "") -> None:
    if ctx.params.get("exit_", False):
        exit(1)
    print(some_txt)

@click.command(context_settings=dict(help_option_names=["-h", "--help"]))
@click.option("--exit","-e", "exit_", is_flag=True, help="exit")
@click.pass_context
def main(ctx: click.Context, exit_: bool) -> None:
    print_or_exit("bla")


if __name__ == "__main__":
    main()

Running the script using the argument -e, then the script exists, without printing to the terminal; when omitting -e, the script prints to the terminal, therefore everything works as expected.

So, why does mypy fail?



from How to fix mypy error when using click's pass_context

No comments:

Post a Comment