Skip to content

Commit 0b8fa09

Browse files
emfdavidpre-commit-ci[bot]svlandeg
authored
✨ Allow annotated parsing with a subclass of Path (#1183)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg <[email protected]>
1 parent f0334c2 commit 0b8fa09

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

tests/test_annotated.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import sys
2+
from pathlib import Path
3+
14
import typer
25
from typer.testing import CliRunner
36
from typing_extensions import Annotated
@@ -76,3 +79,22 @@ def cmd(force: Annotated[bool, typer.Option("--force")] = False):
7679
result = runner.invoke(app, ["--force"])
7780
assert result.exit_code == 0, result.output
7881
assert "Forcing operation" in result.output
82+
83+
84+
def test_annotated_custom_path():
85+
app = typer.Typer()
86+
87+
class CustomPath(Path):
88+
# Subclassing Path was not fully supported before 3.12
89+
# https://docs.python.org/3.12/whatsnew/3.12.html
90+
if sys.version_info < (3, 12):
91+
_flavour = type(Path())._flavour
92+
93+
@app.command()
94+
def custom_parser(
95+
my_path: Annotated[CustomPath, typer.Argument(parser=CustomPath)],
96+
):
97+
assert isinstance(my_path, CustomPath)
98+
99+
result = runner.invoke(app, "/some/quirky/path/implementation")
100+
assert result.exit_code == 0

typer/main.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,9 @@ def determine_type_convertor(type_: Any) -> Optional[Callable[[Any], Any]]:
620620

621621
def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:
622622
if value is not None:
623-
return Path(value)
623+
# allow returning any subclass of Path created by an annotated parser without converting
624+
# it back to a Path
625+
return value if isinstance(value, Path) else Path(value)
624626
return None
625627

626628

0 commit comments

Comments
 (0)