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
Provenance
- Commit
333c28d- Tree
231ec9a- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
7df2f82- Parent 2
051725f
14 files changed+134 added−70 removed
modified:docs/handling-files.md+1 added-2 removed
86 unmodified lines87888990919291929394956 unmodified lines86 unmodified lines
File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:
- A failure at first IO operation will happen by raising an {exc}`FileError`.- It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call {meth}`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for- It can help minimize resource handling confusion by lazily closing it. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the {func}`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).
6 unmodified linesmodified:docs/utils.md-27 removed
257 unmodified lines258 ```python259 click.echo(f"Path: {click.format_filename(b'foo.txt')}")260 ```261 262-## Standard Streams263-264-For command line utilities, it's very important to get access to input and output streams reliably. Python generally265-provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between266-2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.267-268-Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce269-consistent results with different Python versions and for a wide variety of terminal configurations.270-271-The end result is that these functions will always return a functional stream object (except in very odd cases; see272-{doc}`/unicode-support`).273-274-Example:275-276-```python277-import click278-279-stdin_text = click.get_text_stream('stdin')280-stdout_binary = click.get_binary_stream('stdout')281-```282-283-```{versionadded} 6.0284-```285-286-Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more287-information see {doc}`wincmd`.288-262 ## Intelligent File Opening263 264 ```{versionadded} 3.0265 ```121 unmodified linesmodified:src/click/__init__.py+20 added-3 removed
68 unmodified lines69 from .types import UUID as UUID70 from .utils import echo as echo71 from .utils import format_filename as format_filename72 from .utils import get_app_dir as get_app_dir73-from .utils import get_binary_stream as get_binary_stream74-from .utils import get_text_stream as get_text_stream73 from .utils import open_file as open_file74 75 76 def __getattr__(name: str) -> object:33 unmodified lines110 return _OptionParser111 112 if name == "__version__":113 import importlib.metadata116- import warnings114 115 warnings.warn(116 "The '__version__' attribute is deprecated and will be removed in"117 " Click 9.1. Use feature detection or"2 unmodified lines120 stacklevel=2,121 )122 return importlib.metadata.version("click")123 124+ if name == "get_binary_stream":125+ from .utils import _get_binary_stream126+127+ 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_stream133+134+ if name == "get_text_stream":135+ from .utils import _get_text_stream136+137+ 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_stream143+144 raise AttributeError(name)modified:src/click/_termui_impl.py+3 added-3 removed
26 unmodified lines27 from ._compat import strip_ansi28 from ._compat import term_len29 from ._compat import WIN30 from .exceptions import ClickException31+from .utils import _KeepOpenFile32 from .utils import echo32-from .utils import KeepOpenFile33 34 V = t.TypeVar("V")35 36 603 unmodified lines640 """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.643 644- 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)649 650 if color is None:651 color = False652 653- yield KeepOpenFile(stream), encoding, color # type: ignore[misc]653+ yield _KeepOpenFile(stream), encoding, color # type: ignore[misc]654 655 656 class Editor:657 def __init__(288 unmodified linesmodified:src/click/core.py+5 added-5 removed
40 unmodified lines41 from .termui import prompt42 from .termui import style43 from .utils import _detect_program_name44 from .utils import _expand_args45+from .utils import _make_default_short_help46+from .utils import _PacifyFlushWrapper47 from .utils import echo46-from .utils import make_default_short_help48 from .utils import make_str48-from .utils import PacifyFlushWrapper49 50 if t.TYPE_CHECKING:51 from typing_extensions import Self52 1185 unmodified lines1238 """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 = ""1245 1246 if self.deprecated:315 unmodified lines1562 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 linesmodified:src/click/termui.py+2 added-2 removed
18 unmodified lines19 from .globals import resolve_color_default20 from .types import Choice21 from .types import convert_type22 from .types import ParamType23+from .utils import _LazyFile24 from .utils import echo24-from .utils import LazyFile25 26 if t.TYPE_CHECKING:27 from ._termui_impl import ProgressBar28 93 unmodified lines122 return f"{prompt}{suffix}"123 124 125 def _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.name128 129 return default130 830 unmodified linesmodified:src/click/types.py+5 added-5 removed
13 unmodified lines14 15 from ._compat import _get_argv_encoding16 from ._compat import open_stream17 from .exceptions import BadParameter18+from .utils import _LazyFile19+from .utils import _safecall20 from .utils import format_filename19-from .utils import LazyFile20-from .utils import safecall21 22 if t.TYPE_CHECKING:23 import typing_extensions as te24 910 unmodified lines935 try:936 lazy = self.resolve_lazy_flag(value)937 938 if lazy:939- lf = LazyFile(939+ lf = _LazyFile(940 value, self.mode, self.encoding, self.errors, atomic=self.atomic941 )942 943 if ctx is not None:11 unmodified lines955 # 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))962 963 return f964 except OSError as e:965 self.fail(410 unmodified linesmodified:src/click/utils.py+56 added-14 removed
31 unmodified lines32 def _posixify(name: str) -> str:33 return "-".join(name.split()).lower()34 35 36-def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37- """Wraps a function so that it swallows exceptions."""36+def _safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37+ """Wraps a function so that it swallows exceptions.38 39+ :meta private:40+ """41+42 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:43 try:44 return func(*args, **kwargs)45 except Exception:12 unmodified lines58 return value.decode("utf-8", "replace")59 return str(value)60 61 59-def make_default_short_help(help: str, max_length: int = 45) -> str:62+def _make_default_short_help(help: str, max_length: int = 45) -> str:63 """Returns a condensed version of help string.64 65 :meta private:66 """44 unmodified lines111 112 return " ".join(words[:i]) + "..."113 114 112-class LazyFile:115+class _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.120+121+ :meta private:122 """123 124 name: str125 mode: str65 unmodified lines191 """192 if self.should_close:193 self.close()194 190- def __enter__(self) -> LazyFile:195+ def __enter__(self) -> _LazyFile:196 return self197 198 def __exit__(199 self,7 unmodified lines207 self.open()208 return iter(self._f) # type: ignore209 210 206-class KeepOpenFile:211+class _KeepOpenFile:212 """Proxy a file object but keep it open across a ``with`` block.213 214 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 lines218 219 Dunder methods are proxied explicitly: implicit special-method lookups220 bypass :meth:`__getattr__`, because Python resolves them on the type rather221 than the instance.222+223+ :meta private:224 """225 226 _file: t.IO[t.Any]227 2 unmodified lines230 231 def __getattr__(self, name: str) -> t.Any:232 return getattr(self._file, name)233 227- def __enter__(self) -> KeepOpenFile:234+ def __enter__(self) -> _KeepOpenFile:235 return self236 237 def __exit__(238 self,106 unmodified lines345 file.write(out) # type: ignore346 file.flush()347 348 342-def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:349+def _get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:350 """Returns a system stream for byte processing.351 352+ .. deprecated:: 8.5.0353+ Will be removed in Click 9.0.354+355 :param name: the name of the stream to open. Valid names are ``'stdin'``,356 ``'stdout'`` and ``'stderr'``357+358+ :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()364 365 354-def get_text_stream(366+def _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.372+373+ .. deprecated:: 8.5.0374+ Will be removed in Click 9.0.375+376+ 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.379 380+381 :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 lines427 .. 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 )433 434 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)435 436 if not should_close:419- f = t.cast("t.IO[t.Any]", KeepOpenFile(f))437+ f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))438 439 return f440 441 87 unmodified lines529 _posixify(app_name),530 )531 532 515-class PacifyFlushWrapper:533+class _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.540+541+ :meta private:542 """543 544 wrapped: t.IO[t.Any]545 117 unmodified lines663 else:664 out.extend(matches)665 666 return out667+668+669+def __getattr__(name: str) -> object:670+ import warnings671+672+ 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}"]687+688+ raise AttributeError(name)modified:tests/test_utils/test_KeepOpenFile.py+1 added-1 removed
4 unmodified lines5 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 lines5 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 lines34 35 if alter:36 value = alter(value)37 38- out = click.utils.make_default_short_help(value, max_length)38+ out = click.utils._make_default_short_help(value, max_length)39 assert out == expectadded:tests/test_deprecations.py+25 added
1+import pytest2+3+import click4+5+6+@pytest.mark.parametrize("module", [click, click.utils], ids=["click", "click.utils"])7+@pytest.mark.parametrize("name", ["get_binary_stream", "get_text_stream"])8+def test_stream_helper_deprecated(module, name):9+ with pytest.warns(DeprecationWarning, match=name):10+ getattr(module, name)11+12+13+@pytest.mark.parametrize(14+ "name",15+ [16+ "LazyFile",17+ "KeepOpenFile",18+ "make_default_short_help",19+ "PacifyFlushWrapper",20+ "safecall",21+ ],22+)23+def 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 lines9 10 import click11 from click.exceptions import ClickException12 from click.testing import CliRunner13+from click.utils import _get_binary_stream14 15 16 def 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 break8 unmodified lines33 34 def 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 break48 unmodified lines91 92 def 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 break661 unmodified linesmodified:CHANGES.md+7 added
34 unmodified lines35 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`46 47 ## Version 8.4.248 49 Released 2026-06-241561 unmodified lines