Skip to content

Commit 971f24e

Browse files
committed
Allow annotated parsing with path subclasses
1 parent 5a8a043 commit 971f24e

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

tests/test_annotated.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from pathlib import Path
2+
13
import typer
24
from typer.testing import CliRunner
35
from typing_extensions import Annotated
@@ -76,3 +78,19 @@ def cmd(force: Annotated[bool, typer.Option("--force")] = False):
7678
result = runner.invoke(app, ["--force"])
7779
assert result.exit_code == 0, result.output
7880
assert "Forcing operation" in result.output
81+
82+
83+
def test_annotated_custom_path():
84+
app = typer.Typer()
85+
86+
class CustomPath(Path):
87+
pass
88+
89+
@app.command()
90+
def custom_parser(
91+
pth: Annotated[CustomPath, typer.Argument(parser=CustomPath)],
92+
):
93+
assert isinstance(pth, CustomPath)
94+
95+
result = runner.invoke(app, "/some/quirky/path/implementation")
96+
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)