Make `click.Path` generic on `path_type` (#3858)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 7944461, 22177f8 · Browse files · 4 files·+70 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+70 added−14 removed
- tests:+39 added−0 removed
- other:+31 added−14 removed
Provenance
- Commit
86949d1- Tree
7361ef6- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
7944461- Parent 2
22177f8
4 files changed+70 added−14 removed
modified:src/click/types.py+29 added-14 removed
43 unmodified lines44 45 _FloatValueT = t.TypeVar("_FloatValueT", bound=float)46 _FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)47 48+if t.TYPE_CHECKING:49+ _PathT_co = te.TypeVar(50+ "_PathT_co", covariant=True, default="str | bytes | os.PathLike[str]"51+ )52+elif sys.version_info >= (3, 13):53+ _PathT_co = t.TypeVar(54+ "_PathT_co", covariant=True, default=str | bytes | os.PathLike[str]55+ )56+else:57+ _PathT_co = t.TypeVar("_PathT_co", covariant=True)58 59+60 class ParamTypeInfoDict(t.TypedDict):61 param_type: str62 name: str63 991 unmodified lines1055 readable: bool1056 allow_dash: bool1057 1058 1048-class Path(ParamType[str | bytes | os.PathLike[str]]):1059+class Path(ParamType[_PathT_co, str | os.PathLike[str]], t.Generic[_PathT_co]):1060 """The ``Path`` type is similar to the :class:`File` type, but1061 returns the filename instead of an open file. Various checks can be1062 enabled to validate the type of file and permissions.1063 14 unmodified lines1078 :param path_type: Convert the incoming path value to this type. If1079 ``None``, keep Python's default, which is ``str``. Useful to1080 convert to :class:`pathlib.Path`.1081 1082+ .. versionchanged:: 8.5.11083+ Reveal the actual type of the value as converted from raw input.1084+1085 .. versionchanged:: 8.11086 Added the ``executable`` parameter.1087 1088 .. versionchanged:: 8.023 unmodified lines1112 writable: bool = False,1113 readable: bool = True,1114 resolve_path: bool = False,1115 allow_dash: bool = False,1102- path_type: type | None = None,1116+ path_type: type[_PathT_co] | None = None,1117 executable: bool = False,1118 ) -> None:1119 self.exists = exists1120 self.file_okay = file_okay2 unmodified lines1123 self.writable = writable1124 self.executable = executable1125 self.resolve_path = resolve_path1126 self.allow_dash = allow_dash1113- self.type: type | None = path_type1127+ self.type: type[_PathT_co] | None = path_type1128 1129 if self.file_okay and not self.dir_okay:1130 self.name = _("file")1131 elif self.dir_okay and not self.file_okay:11 unmodified lines1143 "allow_dash": self.allow_dash,1144 **super().to_info_dict(),1145 }1146 1133- def coerce_path_result(1134- self, value: str | os.PathLike[str]1135- ) -> str | bytes | os.PathLike[str]:1136- if self.type is not None and not isinstance(value, self.type):1137- if self.type is str:1138- return os.fsdecode(value)1139- elif self.type is bytes:1140- return os.fsencode(value)1147+ def coerce_path_result(self, value: str | os.PathLike[str]) -> _PathT_co:1148+ path_type: type[t.Any] | None = self.type1149+ rv: t.Any = value1150+1151+ if path_type is not None and not isinstance(value, path_type):1152+ if path_type is str:1153+ rv = os.fsdecode(value)1154+ elif path_type is bytes:1155+ rv = os.fsencode(value)1156 else:1142- return t.cast("os.PathLike[str]", self.type(value))1157+ rv = path_type(value)1158 1144- return value1159+ return t.cast("_PathT_co", rv)1160 1161 def convert(1162 self,1163 value: str | os.PathLike[str],1164 param: Parameter | None,1165 ctx: Context | None,1151- ) -> str | bytes | os.PathLike[str]:1166+ ) -> _PathT_co:1167 rv = value1168 1169 dash = b"-" if isinstance(rv, bytes) else "-"1170 is_dash = self.file_okay and self.allow_dash and rv == dash267 unmodified linesmodified:tests/test_types/test_Path.py+5 added
2 unmodified lines3 import platform4 import subprocess5 import sys6 import tempfile7+import typing as t8 9 import pytest10 11 import click171 unmodified lines183 )184 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)185 assert result.exception is None186 assert result.return_value == expect187+188+189+def test_path_converted_type_parameter_at_runtime():190+ assert t.get_args(click.Path[pathlib.Path]) == (pathlib.Path,)added:tests/typing/typing_path.py+34 added
1+import os2+import pathlib3+4+from typing_extensions import assert_type5+6+import click7+8+# Without ``path_type``, ``convert`` returns the value it was given.9+assert_type(click.Path().convert("a/b.txt", None, None), str | bytes | os.PathLike[str])10+assert_type(click.prompt("File", type=click.Path()), str | bytes | os.PathLike[str])11+12+# ``path_type`` narrows the converted value's type for ``convert`` and ``prompt``.13+assert_type(click.Path(path_type=str).convert("a/b.txt", None, None), str)14+assert_type(click.Path(path_type=bytes).convert("a/b.txt", None, None), bytes)15+assert_type(16+ click.Path(path_type=pathlib.Path).convert("a/b.txt", None, None), pathlib.Path17+)18+assert_type(click.prompt("File", type=click.Path(path_type=str)), str)19+assert_type(click.prompt("File", type=click.Path(path_type=pathlib.Path)), pathlib.Path)20+21+assert_type(click.Path(path_type=pathlib.Path)("a/b.txt"), pathlib.Path)22+assert_type(click.Path(path_type=pathlib.Path)(None), None)23+24+# The class can be parameterized explicitly.25+param_type: click.Path[pathlib.Path] = click.Path(exists=True, path_type=pathlib.Path)26+assert_type(param_type.convert("a/b.txt", None, None), pathlib.Path)27+assert_type(param_type.coerce_path_result("a/b.txt"), pathlib.Path)28+29+general: click.ParamType[str | bytes | os.PathLike[str]] = click.Path()30+specific: click.ParamType[pathlib.Path] = click.Path(path_type=pathlib.Path)31+32+assert_type(33+ click.Path(path_type=pathlib.Path)(pathlib.PurePosixPath("a/b.txt")), pathlib.Path34+)modified:CHANGES.md+2 added
9 unmodified lines10 column even when the option is hidden. {meth}`Option.get_help_record` still11 returns `None` for hidden options, so help screens are unchanged. {pr}`3821`12 - Document which types are inferred from `default`, and what an unrecognized13 `type` callable does to a command-line value. {issue}`3036` {pr}`3808`14+- `path_type` narrows the converted value's type for `convert` and `prompt`.15+ {issue}`3822` {pr}`3858`16 17 ## Version 8.5.018 19 Released 2026-08-241655 unmodified lines