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
Provenance
- Commit
449d38f- Tree
59643a8- Author
Tin Tvrtković <tinchester@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d17dbc2
14 files changed+157 added−19 removed
modified:requirements/dev.txt-2 removed
28 unmodified lines29 # tox30 # virtualenv31 identify==2.5.2432 # via pre-commit33-nodeenv==1.8.034- # via pre-commit33 pip-compile-multi==2.6.334 # via -r requirements/dev.in35 pip-tools==6.13.036 # via pip-compile-multi26 unmodified linesmodified:requirements/typing.in+1 added
1 mypy2+pyrightmodified: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 lines8 mypy==1.4.19 # via -r requirements/typing.in10 mypy-extensions==1.0.011 # via mypy12+nodeenv==1.8.013+ # via pyright14+pyright==1.1.31715+ # via -r requirements/typing.in16 typing-extensions==4.6.317 # via mypy18+19+# The following packages are considered to be unsafe in a requirements file:20+# setuptoolsmodified:src/click/decorators.py+9 added-14 removed
19 unmodified lines20 21 R = t.TypeVar("R")22 T = t.TypeVar("T")23 _AnyCallable = t.Callable[..., t.Any]24-_Decorator: "te.TypeAlias" = t.Callable[[T], T]24 FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])25 26 27 def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":120 unmodified lines148 ) -> t.Callable[[_AnyCallable], CmdType]:149 ...150 151 153-# 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.overload154 def 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 lines325 326 327 def 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 manually19 unmodified lines353 354 355 def 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 manually17 unmodified lines379 380 return decorator381 382 388-def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:383+def 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.386 387 :param param_decls: One or more option names. Defaults to the single15 unmodified lines403 kwargs.setdefault("help", "Confirm the action without prompting.")404 return option(*param_decls, **kwargs)405 406 412-def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:407+def 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.410 411 :param param_decls: One or more option names. Defaults to the single15 unmodified lines427 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.434 435 If ``version`` is not provided, Click will try to detect it using97 unmodified lines533 kwargs["callback"] = callback534 return option(*param_decls, **kwargs)535 536 542-def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:537+def 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.540 541 This is usually unnecessary, as the ``--help`` option is added to24 unmodified linesadded:tests/typing/typing_aliased_group.py+45 added
1+"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""2+from __future__ import annotations3+4+from typing_extensions import assert_type5+6+import click7+8+9+class 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))}")20+21+ 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, args28+29+30+@click.command(cls=AliasedGroup)31+def cli() -> None:32+ pass33+34+35+assert_type(cli, AliasedGroup)36+37+38+@cli.command()39+def push() -> None:40+ pass41+42+43+@cli.command()44+def pop() -> None:45+ passadded:tests/typing/typing_confirmation_option.py+13 added
1+"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.confirmation_option(prompt="Are you sure you want to drop the db?")9+def dropdb() -> None:10+ click.echo("Dropped all tables!")11+12+13+assert_type(dropdb, click.Command)added:tests/typing/typing_help_option.py+13 added
1+from typing_extensions import assert_type2+3+import click4+5+6+@click.command()7+@click.help_option("-h", "--help")8+def hello() -> None:9+ """Simple program that greets NAME for a total of COUNT times."""10+ click.echo("Hello!")11+12+13+assert_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"""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.option("--count", default=1, help="number of greetings")9+@click.argument("name")10+def hello(count: int, name: str) -> None:11+ for _ in range(count):12+ click.echo(f"Hello {name}!")13+14+15+assert_type(hello, click.Command)added:tests/typing/typing_password_option.py+14 added
1+import codecs2+3+from typing_extensions import assert_type4+5+import click6+7+8+@click.command()9+@click.password_option()10+def encrypt(password: str) -> None:11+ click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")12+13+14+assert_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."""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.option("--count", default=1, help="Number of greetings.")9+@click.option("--name", prompt="Your name", help="The person to greet.")10+def 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}!")14+15+16+assert_type(hello, click.Command)added:tests/typing/typing_version_option.py+15 added
1+"""2+From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3+"""4+from typing_extensions import assert_type5+6+import click7+8+9+@click.command()10+@click.version_option("0.1")11+def hello() -> None:12+ click.echo("Hello World!")13+14+15+assert_type(hello, click.Command)modified:CHANGES.rst+3 added
3 unmodified lines4 -------------5 6 Unreleased7 8+- Fix type hints for ``@click.command()`` and ``@click.option()``. Introduce typing9+ tests. :issue:`2558`10 11+12 Version 8.1.413 -------------14 15 Released 2023-07-061073 unmodified linesmodified:setup.cfg+1 added-1 removed
76 unmodified lines77 # __init__ exports names78 src/click/__init__.py: F40179 80 [mypy]81-files = src/click81+files = src/click, tests/typing82 python_version = 3.783 show_error_codes = True84 disallow_subclassing_any = True85 disallow_untyped_calls = True19 unmodified linesmodified:tox.ini+4 added-1 removed
18 unmodified lines19 commands = pre-commit run --all-files20 21 [testenv:typing]22 deps = -r requirements/typing.txt23-commands = mypy23+commands =24+ mypy25+ pyright --verifytypes click26+ pyright tests/typing27 28 [testenv:docs]29 deps = -r requirements/docs.txt30 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html