Skip to content
Myr

Mark clearly functions private status. Deprecated Python 2 utilities. (#3695)

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

authored by Rowlando13 · committed by GitHub · parents 7df2f82, 051725f · Browse files · 14 files+134 added−70 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+134 added−70 removed

  • tests:+35 added−9 removed
  • other:+99 added−61 removed

14 files+134 added−70 removed

modified:docs/handling-files.md+1 added-2 removed
modified:docs/utils.md-27 removed
257 unmodified lines
258```python259click.echo(f"Path: {click.format_filename(b'foo.txt')}")260```261262## Standard Streams263264For command line utilities, it's very important to get access to input and output streams reliably. Python generally265provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2662.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.267268Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce269consistent results with different Python versions and for a wide variety of terminal configurations.270271The end result is that these functions will always return a functional stream object (except in very odd cases; see272{doc}`/unicode-support`).273274Example:275276```python277import click278279stdin_text = click.get_text_stream('stdin')280stdout_binary = click.get_binary_stream('stdout')281```282283```{versionadded} 6.0284```285286Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more287information see {doc}`wincmd`.288262## Intelligent File Opening263264```{versionadded} 3.0265```
121 unmodified lines
modified:src/click/__init__.py+20 added-3 removed
68 unmodified lines
69from .types import UUID as UUID70from .utils import echo as echo71from .utils import format_filename as format_filename72from .utils import get_app_dir as get_app_dir73from .utils import get_binary_stream as get_binary_stream74from .utils import get_text_stream as get_text_stream73from .utils import open_file as open_file747576def __getattr__(name: str) -> object:
33 unmodified lines
110 return _OptionParser111112 if name == "__version__":113 import importlib.metadata116 import warnings114115 warnings.warn(116 "The '__version__' attribute is deprecated and will be removed in"117 " Click 9.1. Use feature detection or"
2 unmodified lines
120 stacklevel=2,121 )122 return importlib.metadata.version("click")123124 if name == "get_binary_stream":125 from .utils import _get_binary_stream126127 warnings.warn(128 "'get_binary_stream' is deprecated and will be removed in Click 9.0.",129 DeprecationWarning,130 stacklevel=2,131 )132 return _get_binary_stream133134 if name == "get_text_stream":135 from .utils import _get_text_stream136137 warnings.warn(138 "'get_text_stream' is deprecated and will be removed in Click 9.0.",139 DeprecationWarning,140 stacklevel=2,141 )142 return _get_text_stream143144 raise AttributeError(name)
modified:src/click/_termui_impl.py+3 added-3 removed
26 unmodified lines
27from ._compat import strip_ansi28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import _KeepOpenFile32from .utils import echo32from .utils import KeepOpenFile3334V = t.TypeVar("V")3536
603 unmodified lines
640 """Simply print unformatted text. This is the ultimate fallback. Don't close the641 output stream in this case, since it's coming from elsewhere rather than our642 internal helpers.643644 The stream is wrapped in :class:`~click.utils.KeepOpenFile` so that, as a644 The stream is wrapped in :class:`~click.utils._KeepOpenFile` so that, as a645 borrowed stream, it is not closed by a ``with`` block. The wrapper that646 :func:`get_pager_file` builds around it is detached rather than closed.647 """648 encoding = get_best_encoding(stream)649650 if color is None:651 color = False652653 yield KeepOpenFile(stream), encoding, color # type: ignore[misc]653 yield _KeepOpenFile(stream), encoding, color # type: ignore[misc]654655656class Editor:657 def __init__(
288 unmodified lines
modified:src/click/core.py+5 added-5 removed
40 unmodified lines
41from .termui import prompt42from .termui import style43from .utils import _detect_program_name44from .utils import _expand_args45from .utils import _make_default_short_help46from .utils import _PacifyFlushWrapper47from .utils import echo46from .utils import make_default_short_help48from .utils import make_str48from .utils import PacifyFlushWrapper4950if t.TYPE_CHECKING:51 from typing_extensions import Self52
1185 unmodified lines
1238 """1239 if self.short_help:1240 text = inspect.cleandoc(self.short_help)1241 elif self.help:1242 text = make_default_short_help(self.help, limit)1242 text = _make_default_short_help(self.help, limit)1243 else:1244 text = ""12451246 if self.deprecated:
315 unmodified lines
1562 e.show()1563 sys.exit(e.exit_code)1564 except OSError as e:1565 if e.errno == errno.EPIPE:1566 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1567 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1566 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1567 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))1568 sys.exit(1)1569 else:1570 raise1571 except Exit as e:
2221 unmodified lines
modified:src/click/termui.py+2 added-2 removed
18 unmodified lines
19from .globals import resolve_color_default20from .types import Choice21from .types import convert_type22from .types import ParamType23from .utils import _LazyFile24from .utils import echo24from .utils import LazyFile2526if t.TYPE_CHECKING:27 from ._termui_impl import ProgressBar28
93 unmodified lines
122 return f"{prompt}{suffix}"123124125def _format_default(default: t.Any) -> t.Any:126 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):126 if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127 return default.name128129 return default130
830 unmodified lines
modified:src/click/types.py+5 added-5 removed
13 unmodified lines
1415from ._compat import _get_argv_encoding16from ._compat import open_stream17from .exceptions import BadParameter18from .utils import _LazyFile19from .utils import _safecall20from .utils import format_filename19from .utils import LazyFile20from .utils import safecall2122if t.TYPE_CHECKING:23 import typing_extensions as te24
910 unmodified lines
935 try:936 lazy = self.resolve_lazy_flag(value)937938 if lazy:939 lf = LazyFile(939 lf = _LazyFile(940 value, self.mode, self.encoding, self.errors, atomic=self.atomic941 )942943 if ctx is not None:
11 unmodified lines
955 # properly close the file. This for instance happens when the956 # type is used with prompts.957 if ctx is not None:958 if should_close:959 ctx.call_on_close(safecall(f.close))959 ctx.call_on_close(_safecall(f.close))960 else:961 ctx.call_on_close(safecall(f.flush))961 ctx.call_on_close(_safecall(f.flush))962963 return f964 except OSError as e:965 self.fail(
410 unmodified lines
modified:src/click/utils.py+56 added-14 removed
31 unmodified lines
32def _posixify(name: str) -> str:33 return "-".join(name.split()).lower()343536def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37 """Wraps a function so that it swallows exceptions."""36def _safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37 """Wraps a function so that it swallows exceptions.3839 :meta private:40 """4142 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:43 try:44 return func(*args, **kwargs)45 except Exception:
12 unmodified lines
58 return value.decode("utf-8", "replace")59 return str(value)606159def make_default_short_help(help: str, max_length: int = 45) -> str:62def _make_default_short_help(help: str, max_length: int = 45) -> str:63 """Returns a condensed version of help string.6465 :meta private:66 """
44 unmodified lines
111112 return " ".join(words[:i]) + "..."113114112class LazyFile:115class _LazyFile:116 """A lazy file works like a regular file but it does not fully open117 the file but it does perform some basic checks early to see if the118 filename parameter does make sense. This is useful for safely opening119 files for writing.120121 :meta private:122 """123124 name: str125 mode: str
65 unmodified lines
191 """192 if self.should_close:193 self.close()194190 def __enter__(self) -> LazyFile:195 def __enter__(self) -> _LazyFile:196 return self197198 def __exit__(199 self,
7 unmodified lines
207 self.open()208 return iter(self._f) # type: ignore209210206class KeepOpenFile:211class _KeepOpenFile:212 """Proxy a file object but keep it open across a ``with`` block.213214 Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that215 leaving a ``with`` block does not close it, as used by :func:`open_file`
2 unmodified lines
218219 Dunder methods are proxied explicitly: implicit special-method lookups220 bypass :meth:`__getattr__`, because Python resolves them on the type rather221 than the instance.222223 :meta private:224 """225226 _file: t.IO[t.Any]227
2 unmodified lines
230231 def __getattr__(self, name: str) -> t.Any:232 return getattr(self._file, name)233227 def __enter__(self) -> KeepOpenFile:234 def __enter__(self) -> _KeepOpenFile:235 return self236237 def __exit__(238 self,
106 unmodified lines
345 file.write(out) # type: ignore346 file.flush()347348342def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:349def _get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:350 """Returns a system stream for byte processing.351352 .. deprecated:: 8.5.0353 Will be removed in Click 9.0.354355 :param name: the name of the stream to open. Valid names are ``'stdin'``,356 ``'stdout'`` and ``'stderr'``357358 :meta private:359 """360 opener = binary_streams.get(name)361 if opener is None:362 raise TypeError(_("Unknown standard stream '{name}'").format(name=name))363 return opener()364365354def get_text_stream(366def _get_text_stream(367 name: t.Literal["stdin", "stdout", "stderr"],368 encoding: str | None = None,369 errors: str | None = "strict",370) -> t.TextIO:359 """Returns a system stream for text processing. This usually returns360 a wrapped stream around a binary stream returned from371 """Returns a system stream for text processing.372373 .. deprecated:: 8.5.0374 Will be removed in Click 9.0.375376 This usually returns a wrapped stream around a binary stream returned from377 :func:`get_binary_stream` but it also can take shortcuts for already378 correctly configured streams.379380381 :param name: the name of the stream to open. Valid names are ``'stdin'``,382 ``'stdout'`` and ``'stderr'``383 :param encoding: overrides the detected default encoding.384 :param errors: overrides the default error mode.385 :meta private:386 """387 opener = text_streams.get(name)388 if opener is None:389 raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
37 unmodified lines
427 .. versionadded:: 3.0428 """429 if lazy:430 return t.cast(413 "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)431 "t.IO[t.Any]", _LazyFile(filename, mode, encoding, errors, atomic=atomic)432 )433434 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)435436 if not should_close:419 f = t.cast("t.IO[t.Any]", KeepOpenFile(f))437 f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))438439 return f440441
87 unmodified lines
529 _posixify(app_name),530 )531532515class PacifyFlushWrapper:533class _PacifyFlushWrapper:534 """This wrapper is used to catch and suppress BrokenPipeErrors resulting535 from ``.flush()`` being called on broken pipe during the shutdown/final-GC536 of the Python interpreter. Notably ``.flush()`` is always called on537 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any538 other cleanup code, and the case where the underlying file is not a broken539 pipe, all calls and attributes are proxied.540541 :meta private:542 """543544 wrapped: t.IO[t.Any]545
117 unmodified lines
663 else:664 out.extend(matches)665666 return out667668669def __getattr__(name: str) -> object:670 import warnings671672 if name in {673 "LazyFile",674 "KeepOpenFile",675 "make_default_short_help",676 "PacifyFlushWrapper",677 "safecall",678 "get_text_stream",679 "get_binary_stream",680 }:681 warnings.warn(682 f"'click.utils.{name}' is deprecated and will be removed in Click 9.0.",683 DeprecationWarning,684 stacklevel=2,685 )686 return globals()[f"_{name}"]687688 raise AttributeError(name)
modified:tests/test_utils/test_KeepOpenFile.py+1 added-1 removed
4 unmodified lines
5 expected = list(map(str, range(10)))6 p = tmpdir.mkdir("testdir").join("testfile")7 p.write("\n".join(expected))8 with p.open() as f:9 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):9 for e_line, a_line in zip(expected, click.utils._KeepOpenFile(f), strict=False):10 assert e_line == a_line.strip()
modified:tests/test_utils/test_LazyFile.py+1 added-1 removed
4 unmodified lines
5 expected = list(map(str, range(10)))6 p = tmpdir.mkdir("testdir").join("testfile")7 p.write("\n".join(expected))8 with p.open() as f:9 with click.utils.LazyFile(f.name) as lf:9 with click.utils._LazyFile(f.name) as lf:10 for e_line, a_line in zip(expected, lf, strict=False):11 assert e_line == a_line.strip()
modified:tests/test_utils/test_make_default_short_help.py+1 added-1 removed
33 unmodified lines
3435 if alter:36 value = alter(value)3738 out = click.utils.make_default_short_help(value, max_length)38 out = click.utils._make_default_short_help(value, max_length)39 assert out == expect
added:tests/test_deprecations.py+25 added
1import pytest23import click456@pytest.mark.parametrize("module", [click, click.utils], ids=["click", "click.utils"])7@pytest.mark.parametrize("name", ["get_binary_stream", "get_text_stream"])8def test_stream_helper_deprecated(module, name):9 with pytest.warns(DeprecationWarning, match=name):10 getattr(module, name)111213@pytest.mark.parametrize(14 "name",15 [16 "LazyFile",17 "KeepOpenFile",18 "make_default_short_help",19 "PacifyFlushWrapper",20 "safecall",21 ],22)23def test_utilities_deprecated(name):24 with pytest.warns(DeprecationWarning, match=name):25 getattr(click.utils, name)
modified:tests/test_testing.py+7 added-6 removed
8 unmodified lines
910import click11from click.exceptions import ClickException12from click.testing import CliRunner13from click.utils import _get_binary_stream141516def test_runner():17 @click.command()18 def test():18 i = click.get_binary_stream("stdin")19 o = click.get_binary_stream("stdout")19 i = _get_binary_stream("stdin")20 o = _get_binary_stream("stdout")21 while True:22 chunk = i.read(4096)23 if not chunk:24 break
8 unmodified lines
3334def test_echo_stdin_stream():35 @click.command()36 def test():36 i = click.get_binary_stream("stdin")37 o = click.get_binary_stream("stdout")37 i = _get_binary_stream("stdin")38 o = _get_binary_stream("stdout")39 while True:40 chunk = i.read(4096)41 if not chunk:42 break
48 unmodified lines
9192def test_runner_with_stream():93 @click.command()94 def test():94 i = click.get_binary_stream("stdin")95 o = click.get_binary_stream("stdout")95 i = _get_binary_stream("stdin")96 o = _get_binary_stream("stdout")97 while True:98 chunk = i.read(4096)99 if not chunk:100 break
661 unmodified lines
modified:CHANGES.md+7 added
34 unmodified lines
35 validation steps in `Option.__init__` move into focused helpers, and36 `flag_value` and `default` keep their unset sentinel at construction37 (resolved lazily on read) so `is UNSET` reliably tells a user-supplied value38 from an auto-derived one. Behavior is unchanged. {pr}`3641`39- {func}`get_binary_stream` and {func}`get_text_stream` are deprecated and40 will be removed in Click 9.0. {issue}`3481` {pr}`3695`41- The following `click.utils` names were never intentionally public and are42 now private (`_`-prefixed). The old names remain available with a43 `DeprecationWarning` until Click 9.0: `LazyFile`, `KeepOpenFile`,44 `make_default_short_help`, `PacifyFlushWrapper`, and `safecall`.45 {issue}`3099` {pr}`3695`4647## Version 8.4.24849Released 2026-06-24
1561 unmodified lines