Skip to content
Myr

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

9 files+49 added−46 removed

modified:src/click/_compat.py+18 added-18 removed
48 unmodified lines
49 except LookupError:50 return False515253def get_best_encoding(stream: t.IO) -> str:53def 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 lines
152 return False153 return True154155156def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:156def _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.163164165def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:165def _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 lines
174 return default175 return True176177178def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:178def _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 lines
192193 return None194195196def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:196def _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 lines
240 ) and _is_compat_stream_attr(stream, "errors", errors)241242243def _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 lines
286 )287288289def _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 lines
302 )303304305def _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 lines
366 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)367368369def _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 lines
384 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 mode390391 # Standard streams first. These are simple because they ignore the392 # atomic flag. Use fsdecode to handle Path("-").
62 unmodified lines
455 os.chmod(tmp_filename, perm) # in case perm includes bits in umask456457 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), True460461462class _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 = False
25 unmodified lines
493def strip_ansi(value: str) -> str:494 return _ansi_re.sub("", value)495496497def _is_jupyter_kernel_output(stream: t.IO) -> bool:497def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:498 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):499 stream = stream._stream500501 return stream.__class__.__module__.startswith("ipykernel.")502503504def 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.stdin
65 unmodified lines
575def term_len(x: str) -> int:576 return len(strip_ansi(x))577578579def isatty(stream: t.IO) -> bool:579def isatty(stream: t.IO[t.Any]) -> bool:580 try:581 return stream.isatty()582 except Exception:583 return False
43 unmodified lines
modified:src/click/_termui_impl.py+1 added-1 removed
91 unmodified lines
92 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)94 self._last_line: t.Optional[str] = None9596 def __enter__(self) -> "ProgressBar":96 def __enter__(self) -> "ProgressBar[V]":97 self.entered = True98 self.render_progress()99 return self100
617 unmodified lines
modified:src/click/core.py+5 added-5 removed
1839 unmodified lines
18401841 if self.command_class and kwargs.get("cls") is None:1842 kwargs["cls"] = self.command_class18431844 func: t.Optional[t.Callable] = None1844 func: t.Optional[t.Callable[..., t.Any]] = None18451846 if args and callable(args[0]):1847 assert (1848 len(args) == 1 and not kwargs
39 unmodified lines
1888 Added the :attr:`group_class` attribute.1889 """1890 from .decorators import group18911892 func: t.Optional[t.Callable] = None1892 func: t.Optional[t.Callable[..., t.Any]] = None18931894 if args and callable(args[0]):1895 assert (1896 len(args) == 1 and not kwargs
362 unmodified lines
2259 """2260 if value is None:2261 return () if self.multiple or self.nargs == -1 else None22622263 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 lines
2276 self.type, param=self, ctx=ctx2277 )2278 elif self.nargs == -1:22792280 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))22822283 else: # nargs > 122842285 def convert(value: t.Any) -> t.Tuple:2285 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2286 value = tuple(check_iter(value))22872288 if len(value) != self.nargs:2289 raise BadParameter(
709 unmodified lines
modified:src/click/decorators.py+1 added-1 removed
39 unmodified lines
40 return update_wrapper(t.cast(F, new_func), f)414243def 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 type
449 unmodified lines
modified:src/click/exceptions.py+2 added-2 removed
34 unmodified lines
3536 def __str__(self) -> str:37 return self.message3839 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()4243 echo(_("Error: {message}").format(message=self.format_message()), file=file)
14 unmodified lines
58 super().__init__(message)59 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None6162 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 lines
modified:src/click/testing.py+6 added-6 removed
77 unmodified lines
78 return self._mode798081def 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))8788 if rv is not None:89 return rv90
114 unmodified lines
205206 @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 a
86 unmodified lines
300301 default_color = color302303 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 color
40 unmodified lines
349 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 lines
448 )449450 @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 from
23 unmodified lines
modified:src/click/types.py+5 added-5 removed
395 unmodified lines
396 return "DateTime"397398399class _NumberParamTypeBase(ParamType):400 _number_class: t.ClassVar[t.Type]400 _number_class: t.ClassVar[t.Type[t.Any]]401402 def convert(403 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]404 ) -> t.Any:
296 unmodified lines
701702 lazy = self.resolve_lazy_flag(value)703704 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 lines
793 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_okay
141 unmodified lines
943944 :param types: a list of types that should be used for the tuple items.945 """946947 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]949950 def to_info_dict(self) -> t.Dict[str, t.Any]:951 info_dict = super().to_info_dict()
122 unmodified lines
modified:src/click/utils.py+10 added-8 removed
118 unmodified lines
119 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]]124125 if filename == "-":126 self._f, self.should_close = open_stream(filename, mode, encoding, errors)127 else:
12 unmodified lines
140 if self._f is not None:141 return repr(self._f)142 return f"<unopened file '{self.name}' {self.mode}>"143144 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 lines
182 return iter(self._f) # type: ignore183184185class KeepOpenFile:186 def __init__(self, file: t.IO) -> None:186 def __init__(self, file: t.IO[t.Any]) -> None:187 self._file = file188189 def __getattr__(self, name: str) -> t.Any:190 return getattr(self._file, name)
148 unmodified lines
339 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 lines
369370 .. 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 )376377 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)378379 if not should_close:378 f = t.cast(t.IO, KeepOpenFile(f))380 f = t.cast(t.IO[t.Any], KeepOpenFile(f))381382 return f383384385def 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 will
68 unmodified lines
459 other cleanup code, and the case where the underlying file is not a broken460 pipe, all calls and attributes are proxied.461 """462461 def __init__(self, wrapped: t.IO) -> None:463 def __init__(self, wrapped: t.IO[t.Any]) -> None:464 self.wrapped = wrapped465466 def flush(self) -> None:467 try:
115 unmodified lines
modified:setup.cfg+1 added
83 unmodified lines
84disallow_subclassing_any = True85disallow_untyped_calls = True86disallow_untyped_defs = True87disallow_incomplete_defs = True88disallow_any_generics = True89check_untyped_defs = True90no_implicit_optional = True91local_partial_types = True92no_implicit_reexport = True
12 unmodified lines