Mark clearly functions private status. Deprecated Python 2 utilities.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Eddie Girling · committed by Eddie Girling · parent b551fe8 · Browse files · 13 files·+109 added−68 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+109 added−68 removed
- tests:+10 added−9 removed
- other:+99 added−59 removed
Provenance
- Commit
7a0a344- Tree
42cde17- Author
Eddie Girling <67291205+Rowlando13@users.noreply.github.com>- Committer
Eddie Girling <67291205+Rowlando13@users.noreply.github.com>- Parent
b551fe8
13 files changed+109 added−68 removed
modified:docs/handling-files.md+1 added-1 removed
87 unmodified lines888990919292939495966 unmodified lines87 unmodified linesFile 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 {meth}`_LazyFile.close_intelligently` to help figure out if the file needs closing or not. 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-13 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+ """38+ Wraps a function so that it swallows exceptions.39 40+ :meta private:41+ """42+43 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:44 try:45 return func(*args, **kwargs)46 except Exception:12 unmodified lines59 return value.decode("utf-8", "replace")60 return str(value)61 62 59-def make_default_short_help(help: str, max_length: int = 45) -> str:63+def _make_default_short_help(help: str, max_length: int = 45) -> str:64 """Returns a condensed version of help string.65 66 :meta private:67 """44 unmodified lines112 113 return " ".join(words[:i]) + "..."114 115 112-class LazyFile:113- """A lazy file works like a regular file but it does not fully open116+class _LazyFile:117+ """118+ A lazy file works like a regular file but it does not fully open119 the file but it does perform some basic checks early to see if the120 filename parameter does make sense. This is useful for safely opening121 files for writing.122+123+ :meta private:124+125 """126 127 name: str128 mode: str65 unmodified lines194 """195 if self.should_close:196 self.close()197 190- def __enter__(self) -> LazyFile:198+ def __enter__(self) -> _LazyFile:199 return self200 201 def __exit__(202 self,7 unmodified lines210 self.open()211 return iter(self._f) # type: ignore212 213 206-class KeepOpenFile:214+class _KeepOpenFile:215 """Proxy a file object but keep it open across a ``with`` block.216 217 Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that218 leaving a ``with`` block does not close it, as used by :func:`open_file`2 unmodified lines221 222 Dunder methods are proxied explicitly: implicit special-method lookups223 bypass :meth:`__getattr__`, because Python resolves them on the type rather224 than the instance.225+226+ :meta private:227 """228 229 _file: t.IO[t.Any]230 2 unmodified lines233 234 def __getattr__(self, name: str) -> t.Any:235 return getattr(self._file, name)236 227- def __enter__(self) -> KeepOpenFile:237+ def __enter__(self) -> _KeepOpenFile:238 return self239 240 def __exit__(241 self,109 unmodified lines351 352 def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:353 """Returns a system stream for byte processing.354 355+ .. deprecated:: 8.5356+ Will be removed in Click 9.0.357+358 :param name: the name of the stream to open. Valid names are ``'stdin'``,359 ``'stdout'`` and ``'stderr'``360+361+ :meta private:362 """363 opener = binary_streams.get(name)364 if opener is None:365 raise TypeError(_("Unknown standard stream '{name}'").format(name=name))4 unmodified lines370 name: t.Literal["stdin", "stdout", "stderr"],371 encoding: str | None = None,372 errors: str | None = "strict",373 ) -> t.TextIO:359- """Returns a system stream for text processing. This usually returns360- a wrapped stream around a binary stream returned from374+ """Returns a system stream for text processing.375+376+ .. deprecated:: 8.5377+ Will be removed in Click 9.0.378+379+ This usually returns a wrapped stream around a binary stream returned from380 :func:`get_binary_stream` but it also can take shortcuts for already381 correctly configured streams.382 383+ :meta private:384 :param name: the name of the stream to open. Valid names are ``'stdin'``,385 ``'stdout'`` and ``'stderr'``386 :param encoding: overrides the detected default encoding.387 :param errors: overrides the default error mode.41 unmodified lines429 .. versionadded:: 3.0430 """431 if lazy:432 return t.cast(413- "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)433+ "t.IO[t.Any]", _LazyFile(filename, mode, encoding, errors, atomic=atomic)434 )435 436 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)437 438 if not should_close:419- f = t.cast("t.IO[t.Any]", KeepOpenFile(f))439+ f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))440 441 return f442 443 87 unmodified lines531 _posixify(app_name),532 )533 534 515-class PacifyFlushWrapper:535+class _PacifyFlushWrapper:536 """This wrapper is used to catch and suppress BrokenPipeErrors resulting537 from ``.flush()`` being called on broken pipe during the shutdown/final-GC538 of the Python interpreter. Notably ``.flush()`` is always called on539 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any540 other cleanup code, and the case where the underlying file is not a broken541 pipe, all calls and attributes are proxied.542+543+ :meta private:544 """545 546 wrapped: t.IO[t.Any]547 117 unmodified lines665 else:666 out.extend(matches)667 668 return out669+670+671+def __getattr__(name: str) -> object:672+ import warnings673+674+ if name in {675+ "LazyFile",676+ "KeepOpenFile",677+ "make_default_short_help",678+ "PacifyFlushWrapper",679+ "safecall",680+ }:681+ warnings.warn(682+ f"'click.utils.{name}' was never intentionally public and will be"683+ " renamed in Click 9.0.",684+ DeprecationWarning,685+ stacklevel=2,686+ )687+ return globals()[f"_{name}"]688+689+ 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 == expectmodified: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
30 unmodified lines31 validation steps in `Option.__init__` move into focused helpers, and32 `flag_value` and `default` keep their unset sentinel at construction33 (resolved lazily on read) so `is UNSET` reliably tells a user-supplied value34 from an auto-derived one. Behavior is unchanged. {pr}`3641`35+- {func}`get_binary_stream` and {func}`get_text_stream` are deprecated and36+ will be removed in Click 9.0. {issue}`3481` {pr}`3695`37+- The following `click.utils` names were never intentionally public and are38+ now private (`_`-prefixed). The old names remain available with a39+ `DeprecationWarning` until Click 9.0: `LazyFile`, `KeepOpenFile`,40+ `make_default_short_help`, `PacifyFlushWrapper`, and `safecall`.41+ {issue}`3099` {pr}`3695`42 43 ## Version 8.4.244 45 Released 2026-06-241561 unmodified lines