Skip to content
Myr

Fix types, introduce type tests (#2562)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tin Tvrtković · committed by GitHub · parent d17dbc2 · Browse files · 14 files+157 added−19 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+157 added−19 removed

  • tests:+131 added−0 removed
  • other:+26 added−19 removed

14 files+157 added−19 removed

modified:requirements/dev.txt-2 removed
28 unmodified lines
29 # tox30 # virtualenv31identify==2.5.2432 # via pre-commit33nodeenv==1.8.034 # via pre-commit33pip-compile-multi==2.6.334 # via -r requirements/dev.in35pip-tools==6.13.036 # via pip-compile-multi
26 unmodified lines
modified:requirements/typing.in+1 added
1mypy2pyright
modified:requirements/typing.txt+8 added-1 removed
1# SHA1:7983aaa01d64547827c20395d77e248c41b2572f1# SHA1:0d25c235a98f3c8c55aefb59b91c82834e185f0a2#3# This file is autogenerated by pip-compile-multi4# To update, run:5#
2 unmodified lines
8mypy==1.4.19 # via -r requirements/typing.in10mypy-extensions==1.0.011 # via mypy12nodeenv==1.8.013 # via pyright14pyright==1.1.31715 # via -r requirements/typing.in16typing-extensions==4.6.317 # via mypy1819# The following packages are considered to be unsafe in a requirements file:20# setuptools
modified:src/click/decorators.py+9 added-14 removed
19 unmodified lines
2021R = t.TypeVar("R")22T = t.TypeVar("T")23_AnyCallable = t.Callable[..., t.Any]24_Decorator: "te.TypeAlias" = t.Callable[[T], T]24FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])252627def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":
120 unmodified lines
148) -> t.Callable[[_AnyCallable], CmdType]:149 ...150151153# variant: name omitted, cls _must_ be a keyword argument, @command(cmd=CommandCls, ...)154# The correct way to spell this overload is to use keyword-only argument syntax:155# def command(*, cls: t.Type[CmdType], **attrs: t.Any) -> ...156# However, mypy thinks this doesn't fit the overloaded function. Pyright does157# accept that spelling, and the following work-around makes pyright issue a158# warning that CmdType could be left unsolved, but mypy sees it as fine. *shrug*152# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)153@t.overload154def command(155 name: None = None,156 *,162 cls: t.Type[CmdType] = ...,157 cls: t.Type[CmdType],158 **attrs: t.Any,159) -> t.Callable[[_AnyCallable], CmdType]:160 ...161
163 unmodified lines
325326327def argument(328 *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any334) -> _Decorator[FC]:329) -> t.Callable[[FC], FC]:330 """Attaches an argument to the command. All positional arguments are331 passed as parameter declarations to :class:`Argument`; all keyword332 arguments are forwarded unchanged (except ``cls``).333 This is equivalent to creating an :class:`Argument` instance manually
19 unmodified lines
353354355def option(356 *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any362) -> _Decorator[FC]:357) -> t.Callable[[FC], FC]:358 """Attaches an option to the command. All positional arguments are359 passed as parameter declarations to :class:`Option`; all keyword360 arguments are forwarded unchanged (except ``cls``).361 This is equivalent to creating an :class:`Option` instance manually
17 unmodified lines
379380 return decorator381382388def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:383def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:384 """Add a ``--yes`` option which shows a prompt before continuing if385 not passed. If the prompt is declined, the program will exit.386387 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
403 kwargs.setdefault("help", "Confirm the action without prompting.")404 return option(*param_decls, **kwargs)405406412def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:407def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:408 """Add a ``--password`` option which prompts for a password, hiding409 input and asking to enter the value again for confirmation.410411 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
427 package_name: t.Optional[str] = None,428 prog_name: t.Optional[str] = None,429 message: t.Optional[str] = None,430 **kwargs: t.Any,436) -> _Decorator[FC]:431) -> t.Callable[[FC], FC]:432 """Add a ``--version`` option which immediately prints the version433 number and exits the program.434435 If ``version`` is not provided, Click will try to detect it using
97 unmodified lines
533 kwargs["callback"] = callback534 return option(*param_decls, **kwargs)535536542def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:537def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:538 """Add a ``--help`` option which immediately prints the help page539 and exits the program.540541 This is usually unnecessary, as the ``--help`` option is added to
24 unmodified lines
added:tests/typing/typing_aliased_group.py+45 added
1"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""2from __future__ import annotations34from typing_extensions import assert_type56import click789class AliasedGroup(click.Group):10 def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:11 rv = click.Group.get_command(self, ctx, cmd_name)12 if rv is not None:13 return rv14 matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)]15 if not matches:16 return None17 elif len(matches) == 1:18 return click.Group.get_command(self, ctx, matches[0])19 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")2021 def resolve_command(22 self, ctx: click.Context, args: list[str]23 ) -> tuple[str | None, click.Command, list[str]]:24 # always return the full command name25 _, cmd, args = super().resolve_command(ctx, args)26 assert cmd is not None27 return cmd.name, cmd, args282930@click.command(cls=AliasedGroup)31def cli() -> None:32 pass333435assert_type(cli, AliasedGroup)363738@cli.command()39def push() -> None:40 pass414243@cli.command()44def pop() -> None:45 pass
added:tests/typing/typing_confirmation_option.py+13 added
1"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""2from typing_extensions import assert_type34import click567@click.command()8@click.confirmation_option(prompt="Are you sure you want to drop the db?")9def dropdb() -> None:10 click.echo("Dropped all tables!")111213assert_type(dropdb, click.Command)
added:tests/typing/typing_help_option.py+13 added
1from typing_extensions import assert_type23import click456@click.command()7@click.help_option("-h", "--help")8def hello() -> None:9 """Simple program that greets NAME for a total of COUNT times."""10 click.echo("Hello!")111213assert_type(hello, click.Command)
added:tests/typing/typing_options.py+15 added
1"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters"""2from typing_extensions import assert_type34import click567@click.command()8@click.option("--count", default=1, help="number of greetings")9@click.argument("name")10def hello(count: int, name: str) -> None:11 for _ in range(count):12 click.echo(f"Hello {name}!")131415assert_type(hello, click.Command)
added:tests/typing/typing_password_option.py+14 added
1import codecs23from typing_extensions import assert_type45import click678@click.command()9@click.password_option()10def encrypt(password: str) -> None:11 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")121314assert_type(encrypt, click.Command)
added:tests/typing/typing_simple_example.py+16 added
1"""The simple example from https://github.com/pallets/click#a-simple-example."""2from typing_extensions import assert_type34import click567@click.command()8@click.option("--count", default=1, help="Number of greetings.")9@click.option("--name", prompt="Your name", help="The person to greet.")10def hello(count: int, name: str) -> None:11 """Simple program that greets NAME for a total of COUNT times."""12 for _ in range(count):13 click.echo(f"Hello, {name}!")141516assert_type(hello, click.Command)
added:tests/typing/typing_version_option.py+15 added
1"""2From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3"""4from typing_extensions import assert_type56import click789@click.command()10@click.version_option("0.1")11def hello() -> None:12 click.echo("Hello World!")131415assert_type(hello, click.Command)
modified:CHANGES.rst+3 added
3 unmodified lines
4-------------56Unreleased78- Fix type hints for ``@click.command()`` and ``@click.option()``. Introduce typing9 tests. :issue:`2558`101112Version 8.1.413-------------1415Released 2023-07-06
1073 unmodified lines
modified:setup.cfg+1 added-1 removed
76 unmodified lines
77 # __init__ exports names78 src/click/__init__.py: F4017980[mypy]81files = src/click81files = src/click, tests/typing82python_version = 3.783show_error_codes = True84disallow_subclassing_any = True85disallow_untyped_calls = True
19 unmodified lines
modified:tox.ini+4 added-1 removed
18 unmodified lines
19commands = pre-commit run --all-files2021[testenv:typing]22deps = -r requirements/typing.txt23commands = mypy23commands =24 mypy25 pyright --verifytypes click26 pyright tests/typing2728[testenv:docs]29deps = -r requirements/docs.txt30commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html