Skip to content
Myr

`path_type` narrows the converted value's type for `convert` and `prompt`

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

Closes #3822

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 7944461 · 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

4 files+70 added−14 removed

modified:src/click/types.py+29 added-14 removed
43 unmodified lines
4445_FloatValueT = t.TypeVar("_FloatValueT", bound=float)46_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)4748if t.TYPE_CHECKING:49 _PathT_co = te.TypeVar(50 "_PathT_co", covariant=True, default="str | bytes | os.PathLike[str]"51 )52elif sys.version_info >= (3, 13):53 _PathT_co = t.TypeVar(54 "_PathT_co", covariant=True, default=str | bytes | os.PathLike[str]55 )56else:57 _PathT_co = t.TypeVar("_PathT_co", covariant=True)585960class ParamTypeInfoDict(t.TypedDict):61 param_type: str62 name: str63
991 unmodified lines
1055 readable: bool1056 allow_dash: bool105710581048class Path(ParamType[str | bytes | os.PathLike[str]]):1059class 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 lines
1078 :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`.10811082 .. versionchanged:: 8.5.11083 Reveal the actual type of the value as converted from raw input.10841085 .. versionchanged:: 8.11086 Added the ``executable`` parameter.10871088 .. versionchanged:: 8.0
23 unmodified lines
1112 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_okay
2 unmodified lines
1123 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_type11281129 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 lines
1143 "allow_dash": self.allow_dash,1144 **super().to_info_dict(),1145 }11461133 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 = value11501151 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)11581144 return value1159 return t.cast("_PathT_co", rv)11601161 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 = value11681169 dash = b"-" if isinstance(rv, bytes) else "-"1170 is_dash = self.file_okay and self.allow_dash and rv == dash
267 unmodified lines
modified:tests/test_types/test_Path.py+5 added
2 unmodified lines
3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click
171 unmodified lines
183 )184 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)185 assert result.exception is None186 assert result.return_value == expect187188189def 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
1import os2import pathlib34from typing_extensions import assert_type56import click78# Without ``path_type``, ``convert`` returns the value it was given.9assert_type(click.Path().convert("a/b.txt", None, None), str | bytes | os.PathLike[str])10assert_type(click.prompt("File", type=click.Path()), str | bytes | os.PathLike[str])1112# ``path_type`` narrows the converted value's type for ``convert`` and ``prompt``.13assert_type(click.Path(path_type=str).convert("a/b.txt", None, None), str)14assert_type(click.Path(path_type=bytes).convert("a/b.txt", None, None), bytes)15assert_type(16 click.Path(path_type=pathlib.Path).convert("a/b.txt", None, None), pathlib.Path17)18assert_type(click.prompt("File", type=click.Path(path_type=str)), str)19assert_type(click.prompt("File", type=click.Path(path_type=pathlib.Path)), pathlib.Path)2021assert_type(click.Path(path_type=pathlib.Path)("a/b.txt"), pathlib.Path)22assert_type(click.Path(path_type=pathlib.Path)(None), None)2324# The class can be parameterized explicitly.25param_type: click.Path[pathlib.Path] = click.Path(exists=True, path_type=pathlib.Path)26assert_type(param_type.convert("a/b.txt", None, None), pathlib.Path)27assert_type(param_type.coerce_path_result("a/b.txt"), pathlib.Path)2829general: click.ParamType[str | bytes | os.PathLike[str]] = click.Path()30specific: click.ParamType[pathlib.Path] = click.Path(path_type=pathlib.Path)3132assert_type(33 click.Path(path_type=pathlib.Path)(pathlib.PurePosixPath("a/b.txt")), pathlib.Path34)
modified:CHANGES.md+2 added
9 unmodified lines
10 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`1617## Version 8.5.01819Released 2026-08-24
1655 unmodified lines