Skip to content
Myr

✨ Allow annotated parsing with a subclass of `Path` (#1183)

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

authored by David Stuebe · committed by GitHub · parent f0334c2 · Browse files · 2 files+25 added−1 removed
This commit

State

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

Trailers

  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Co-authored-by: svlandeg <svlandeg@github.com>

Diff stats

2 files+25 added−1 removed

  • tests:+22 added−0 removed
  • other:+3 added−1 removed

2 files+25 added−1 removed

modified:tests/test_annotated.py+22 added
1import sys2from pathlib import Path34import typer5from typer.testing import CliRunner6from typing_extensions import Annotated7
70 unmodified lines
7879 result = runner.invoke(app, ["--force"])80 assert result.exit_code == 0, result.output81 assert "Forcing operation" in result.output828384def test_annotated_custom_path():85 app = typer.Typer()8687 class CustomPath(Path):88 # Subclassing Path was not fully supported before 3.1289 # https://docs.python.org/3.12/whatsnew/3.12.html90 if sys.version_info < (3, 12):91 _flavour = type(Path())._flavour9293 @app.command()94 def custom_parser(95 my_path: Annotated[CustomPath, typer.Argument(parser=CustomPath)],96 ):97 assert isinstance(my_path, CustomPath)9899 result = runner.invoke(app, "/some/quirky/path/implementation")100 assert result.exit_code == 0
modified:typer/main.py+3 added-1 removed
618 unmodified lines
619620621def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:622 if value is not None:623 return Path(value)623 # allow returning any subclass of Path created by an annotated parser without converting624 # it back to a Path625 return value if isinstance(value, Path) else Path(value)626 return None627628629def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:
516 unmodified lines