Skip to content
Myr

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

13 files+109 added−68 removed

modified:docs/handling-files.md+1 added-1 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-13 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 """38 Wraps a function so that it swallows exceptions.3940 :meta private:41 """4243 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:44 try:45 return func(*args, **kwargs)46 except Exception:
12 unmodified lines
59 return value.decode("utf-8", "replace")60 return str(value)616259def make_default_short_help(help: str, max_length: int = 45) -> str:63def _make_default_short_help(help: str, max_length: int = 45) -> str:64 """Returns a condensed version of help string.6566 :meta private:67 """
44 unmodified lines
112113 return " ".join(words[:i]) + "..."114115112class LazyFile:113 """A lazy file works like a regular file but it does not fully open116class _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.122123 :meta private:124125 """126127 name: str128 mode: str
65 unmodified lines
194 """195 if self.should_close:196 self.close()197190 def __enter__(self) -> LazyFile:198 def __enter__(self) -> _LazyFile:199 return self200201 def __exit__(202 self,
7 unmodified lines
210 self.open()211 return iter(self._f) # type: ignore212213206class KeepOpenFile:214class _KeepOpenFile:215 """Proxy a file object but keep it open across a ``with`` block.216217 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 lines
221222 Dunder methods are proxied explicitly: implicit special-method lookups223 bypass :meth:`__getattr__`, because Python resolves them on the type rather224 than the instance.225226 :meta private:227 """228229 _file: t.IO[t.Any]230
2 unmodified lines
233234 def __getattr__(self, name: str) -> t.Any:235 return getattr(self._file, name)236227 def __enter__(self) -> KeepOpenFile:237 def __enter__(self) -> _KeepOpenFile:238 return self239240 def __exit__(241 self,
109 unmodified lines
351352def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:353 """Returns a system stream for byte processing.354355 .. deprecated:: 8.5356 Will be removed in Click 9.0.357358 :param name: the name of the stream to open. Valid names are ``'stdin'``,359 ``'stdout'`` and ``'stderr'``360361 :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 lines
370 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.375376 .. deprecated:: 8.5377 Will be removed in Click 9.0.378379 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.382383 :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 lines
429 .. 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 )435436 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)437438 if not should_close:419 f = t.cast("t.IO[t.Any]", KeepOpenFile(f))439 f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))440441 return f442443
87 unmodified lines
531 _posixify(app_name),532 )533534515class PacifyFlushWrapper:535class _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.542543 :meta private:544 """545546 wrapped: t.IO[t.Any]547
117 unmodified lines
665 else:666 out.extend(matches)667668 return out669670671def __getattr__(name: str) -> object:672 import warnings673674 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}"]688689 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
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
30 unmodified lines
31 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`4243## Version 8.4.24445Released 2026-06-24
1561 unmodified lines