Types: don't leave generic types without a parameter
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Enable `disallow_any_generics` and provide type information for missing parameters for type hints.
authored by Martijn Pieters · committed by David Lord · parent a6c7ee0 · Browse files · 9 files·+49 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+49 added−46 removed
- other:+49 added−46 removed
Provenance
- Commit
a1093bb- Tree
25c1680- Author
Martijn Pieters <mj@zopatista.com>- Committer
David Lord <davidism@gmail.com>- Parent
a6c7ee0
9 files changed+49 added−46 removed
modified:src/click/_compat.py+18 added-18 removed
48 unmodified lines49 except LookupError:50 return False51 52 53-def get_best_encoding(stream: t.IO) -> str:53+def get_best_encoding(stream: t.IO[t.Any]) -> str:54 """Returns the default stream encoding if not found."""55 rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()56 if is_ascii_encoding(rv):57 return "utf-8"94 unmodified lines152 return False153 return True154 155 156-def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:156+def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:157 try:158 return isinstance(stream.read(0), bytes)159 except Exception:160 return default161 # This happens in some cases where the stream was already162 # closed. In this case, we assume the default.163 164 165-def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:165+def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:166 try:167 stream.write(b"")168 except Exception:169 try:4 unmodified lines174 return default175 return True176 177 178-def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:178+def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:179 # We need to figure out if the given stream is already binary.180 # This can happen because the official docs recommend detaching181 # the streams to get binary streams. Some code might do this, so182 # we need to deal with this case explicitly.9 unmodified lines192 193 return None194 195 196-def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:196+def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:197 # We need to figure out if the given stream is already binary.198 # This can happen because the official docs recommend detaching199 # the streams to get binary streams. Some code might do this, so200 # we need to deal with this case explicitly.39 unmodified lines240 ) and _is_compat_stream_attr(stream, "errors", errors)241 242 243 def _force_correct_text_stream(244- text_stream: t.IO,244+ text_stream: t.IO[t.Any],245 encoding: t.Optional[str],246 errors: t.Optional[str],247- is_binary: t.Callable[[t.IO, bool], bool],248- find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]],247+ is_binary: t.Callable[[t.IO[t.Any], bool], bool],248+ find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]],249 force_readable: bool = False,250 force_writable: bool = False,251 ) -> t.TextIO:252 if is_binary(text_stream, False):33 unmodified lines286 )287 288 289 def _force_correct_text_reader(290- text_reader: t.IO,290+ text_reader: t.IO[t.Any],291 encoding: t.Optional[str],292 errors: t.Optional[str],293 force_readable: bool = False,294 ) -> t.TextIO:7 unmodified lines302 )303 304 305 def _force_correct_text_writer(306- text_writer: t.IO,306+ text_writer: t.IO[t.Any],307 encoding: t.Optional[str],308 errors: t.Optional[str],309 force_writable: bool = False,310 ) -> t.TextIO:55 unmodified lines366 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)367 368 369 def _wrap_io_open(370- file: t.Union[str, os.PathLike, int],370+ file: t.Union[str, "os.PathLike[t.AnyStr]", int],371 mode: str,372 encoding: t.Optional[str],373 errors: t.Optional[str],374-) -> t.IO:374+) -> t.IO[t.Any]:375 """Handles not passing ``encoding`` and ``errors`` in binary mode."""376 if "b" in mode:377 return open(file, mode)378 5 unmodified lines384 mode: str = "r",385 encoding: t.Optional[str] = None,386 errors: t.Optional[str] = "strict",387 atomic: bool = False,388-) -> t.Tuple[t.IO, bool]:388+) -> t.Tuple[t.IO[t.Any], bool]:389 binary = "b" in mode390 391 # Standard streams first. These are simple because they ignore the392 # atomic flag. Use fsdecode to handle Path("-").62 unmodified lines455 os.chmod(tmp_filename, perm) # in case perm includes bits in umask456 457 f = _wrap_io_open(fd, mode, encoding, errors)458 af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))459- return t.cast(t.IO, af), True459+ return t.cast(t.IO[t.Any], af), True460 461 462 class _AtomicFile:463- def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None:463+ def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:464 self._f = f465 self._tmp_filename = tmp_filename466 self._real_filename = real_filename467 self.closed = False25 unmodified lines493 def strip_ansi(value: str) -> str:494 return _ansi_re.sub("", value)495 496 497-def _is_jupyter_kernel_output(stream: t.IO) -> bool:497+def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:498 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):499 stream = stream._stream500 501 return stream.__class__.__module__.startswith("ipykernel.")502 503 504 def should_strip_ansi(505- stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None505+ stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None506 ) -> bool:507 if color is None:508 if stream is None:509 stream = sys.stdin65 unmodified lines575 def term_len(x: str) -> int:576 return len(strip_ansi(x))577 578 579-def isatty(stream: t.IO) -> bool:579+def isatty(stream: t.IO[t.Any]) -> bool:580 try:581 return stream.isatty()582 except Exception:583 return False43 unmodified linesmodified:src/click/_termui_impl.py+1 added-1 removed
91 unmodified lines92 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)94 self._last_line: t.Optional[str] = None95 96- def __enter__(self) -> "ProgressBar":96+ def __enter__(self) -> "ProgressBar[V]":97 self.entered = True98 self.render_progress()99 return self100 617 unmodified linesmodified:src/click/core.py+5 added-5 removed
1839 unmodified lines1840 1841 if self.command_class and kwargs.get("cls") is None:1842 kwargs["cls"] = self.command_class1843 1844- func: t.Optional[t.Callable] = None1844+ func: t.Optional[t.Callable[..., t.Any]] = None1845 1846 if args and callable(args[0]):1847 assert (1848 len(args) == 1 and not kwargs39 unmodified lines1888 Added the :attr:`group_class` attribute.1889 """1890 from .decorators import group1891 1892- func: t.Optional[t.Callable] = None1892+ func: t.Optional[t.Callable[..., t.Any]] = None1893 1894 if args and callable(args[0]):1895 assert (1896 len(args) == 1 and not kwargs362 unmodified lines2259 """2260 if value is None:2261 return () if self.multiple or self.nargs == -1 else None2262 2263- def check_iter(value: t.Any) -> t.Iterator:2263+ def check_iter(value: t.Any) -> t.Iterator[t.Any]:2264 try:2265 return _check_iter(value)2266 except TypeError:2267 # This should only happen when passing in args manually,8 unmodified lines2276 self.type, param=self, ctx=ctx2277 )2278 elif self.nargs == -1:2279 2280- def convert(value: t.Any) -> t.Tuple:2280+ def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2281 return tuple(self.type(x, self, ctx) for x in check_iter(value))2282 2283 else: # nargs > 12284 2285- def convert(value: t.Any) -> t.Tuple:2285+ def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2286 value = tuple(check_iter(value))2287 2288 if len(value) != self.nargs:2289 raise BadParameter(709 unmodified linesmodified:src/click/decorators.py+1 added-1 removed
39 unmodified lines40 return update_wrapper(t.cast(F, new_func), f)41 42 43 def make_pass_decorator(44- object_type: t.Type, ensure: bool = False44+ object_type: t.Type[t.Any], ensure: bool = False45 ) -> "t.Callable[[F], F]":46 """Given an object type this creates a decorator that will work47 similar to :func:`pass_obj` but instead of passing the object of the48 current context, it will find the innermost context of type449 unmodified linesmodified:src/click/exceptions.py+2 added-2 removed
34 unmodified lines35 36 def __str__(self) -> str:37 return self.message38 39- def show(self, file: t.Optional[t.IO] = None) -> None:39+ def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:40 if file is None:41 file = get_text_stderr()42 43 echo(_("Error: {message}").format(message=self.format_message()), file=file)14 unmodified lines58 super().__init__(message)59 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None61 62- def show(self, file: t.Optional[t.IO] = None) -> None:62+ def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:63 if file is None:64 file = get_text_stderr()65 color = None66 hint = ""221 unmodified linesmodified:src/click/testing.py+6 added-6 removed
77 unmodified lines78 return self._mode79 80 81 def make_input_stream(82- input: t.Optional[t.Union[str, bytes, t.IO]], charset: str82+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str83 ) -> t.BinaryIO:84 # Is already an input stream.85 if hasattr(input, "read"):86- rv = _find_binary_reader(t.cast(t.IO, input))86+ rv = _find_binary_reader(t.cast(t.IO[t.Any], input))87 88 if rv is not None:89 return rv90 114 unmodified lines205 206 @contextlib.contextmanager207 def isolation(208 self,209- input: t.Optional[t.Union[str, bytes, t.IO]] = None,209+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,210 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,211 color: bool = False,212 ) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:213 """A context manager that sets up the isolation for invoking of a86 unmodified lines300 301 default_color = color302 303 def should_strip_ansi(304- stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None304+ stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None305 ) -> bool:306 if color is None:307 return not default_color308 return not color40 unmodified lines349 def invoke(350 self,351 cli: "BaseCommand",352 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353- input: t.Optional[t.Union[str, bytes, t.IO]] = None,353+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,354 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,355 catch_exceptions: bool = True,356 color: bool = False,357 **extra: t.Any,90 unmodified lines448 )449 450 @contextlib.contextmanager451 def isolated_filesystem(452- self, temp_dir: t.Optional[t.Union[str, os.PathLike]] = None452+ self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None453 ) -> t.Iterator[str]:454 """A context manager that creates a temporary directory and455 changes the current working directory to it. This isolates tests456 that affect the contents of the CWD to prevent them from23 unmodified linesmodified:src/click/types.py+5 added-5 removed
395 unmodified lines396 return "DateTime"397 398 399 class _NumberParamTypeBase(ParamType):400- _number_class: t.ClassVar[t.Type]400+ _number_class: t.ClassVar[t.Type[t.Any]]401 402 def convert(403 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]404 ) -> t.Any:296 unmodified lines701 702 lazy = self.resolve_lazy_flag(value)703 704 if lazy:705- f: t.IO = t.cast(706- t.IO,705+ f: t.IO[t.Any] = t.cast(706+ t.IO[t.Any],707 LazyFile(708 value, self.mode, self.encoding, self.errors, atomic=self.atomic709 ),710 )82 unmodified lines793 writable: bool = False,794 readable: bool = True,795 resolve_path: bool = False,796 allow_dash: bool = False,797- path_type: t.Optional[t.Type] = None,797+ path_type: t.Optional[t.Type[t.Any]] = None,798 executable: bool = False,799 ):800 self.exists = exists801 self.file_okay = file_okay141 unmodified lines943 944 :param types: a list of types that should be used for the tuple items.945 """946 947- def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None:947+ def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:948 self.types = [convert_type(ty) for ty in types]949 950 def to_info_dict(self) -> t.Dict[str, t.Any]:951 info_dict = super().to_info_dict()122 unmodified linesmodified:src/click/utils.py+10 added-8 removed
118 unmodified lines119 self.mode = mode120 self.encoding = encoding121 self.errors = errors122 self.atomic = atomic123- self._f: t.Optional[t.IO]123+ self._f: t.Optional[t.IO[t.Any]]124 125 if filename == "-":126 self._f, self.should_close = open_stream(filename, mode, encoding, errors)127 else:12 unmodified lines140 if self._f is not None:141 return repr(self._f)142 return f"<unopened file '{self.name}' {self.mode}>"143 144- def open(self) -> t.IO:144+ def open(self) -> t.IO[t.Any]:145 """Opens the file if it's not yet open. This call might fail with146 a :exc:`FileError`. Not handling this error will produce an error147 that Click shows.148 """33 unmodified lines182 return iter(self._f) # type: ignore183 184 185 class KeepOpenFile:186- def __init__(self, file: t.IO) -> None:186+ def __init__(self, file: t.IO[t.Any]) -> None:187 self._file = file188 189 def __getattr__(self, name: str) -> t.Any:190 return getattr(self._file, name)148 unmodified lines339 encoding: t.Optional[str] = None,340 errors: t.Optional[str] = "strict",341 lazy: bool = False,342 atomic: bool = False,343-) -> t.IO:343+) -> t.IO[t.Any]:344 """Open a file, with extra behavior to handle ``'-'`` to indicate345 a standard stream, lazy open on write, and atomic write. Similar to346 the behavior of the :class:`~click.File` param type.347 21 unmodified lines369 370 .. versionadded:: 3.0371 """372 if lazy:373- return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic))373+ return t.cast(374+ t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)375+ )376 377 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)378 379 if not should_close:378- f = t.cast(t.IO, KeepOpenFile(f))380+ f = t.cast(t.IO[t.Any], KeepOpenFile(f))381 382 return f383 384 385 def format_filename(384- filename: t.Union[str, bytes, os.PathLike], shorten: bool = False386+ filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False387 ) -> str:388 """Formats a filename for user display. The main purpose of this389 function is to ensure that the filename can be displayed at all. This390 will decode the filename to unicode if necessary in a way that it will68 unmodified lines459 other cleanup code, and the case where the underlying file is not a broken460 pipe, all calls and attributes are proxied.461 """462 461- def __init__(self, wrapped: t.IO) -> None:463+ def __init__(self, wrapped: t.IO[t.Any]) -> None:464 self.wrapped = wrapped465 466 def flush(self) -> None:467 try:115 unmodified linesmodified:setup.cfg+1 added
83 unmodified lines84 disallow_subclassing_any = True85 disallow_untyped_calls = True86 disallow_untyped_defs = True87 disallow_incomplete_defs = True88+disallow_any_generics = True89 check_untyped_defs = True90 no_implicit_optional = True91 local_partial_types = True92 no_implicit_reexport = True12 unmodified lines