-
-
Notifications
You must be signed in to change notification settings - Fork 829
✨ Support Date parameter type (#94) #326
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+222
−11
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| You can specify a *CLI parameter* as a Python <a href="https://docs.python.org/3/library/datetime.html" class="external-link" target="_blank">`date`</a>. | ||
|
|
||
| Your function will receive a standard Python `date` object, and again, your editor will give you completion, etc. | ||
|
|
||
| ```Python hl_lines="2 7 8 9" | ||
| {!../docs_src/parameter_types/date/tutorial001.py!} | ||
| ``` | ||
|
|
||
| Typer will accept any string from the following formats: | ||
|
|
||
| * `%Y-%m-%d` | ||
|
|
||
| Check it: | ||
|
|
||
| <div class="termy"> | ||
|
|
||
| ```console | ||
| $ python main.py --help | ||
|
|
||
| Usage: main.py [OPTIONS] BIRTH:[%Y-%m-%d] | ||
|
|
||
| Arguments: | ||
| BIRTH:[%Y-%m-%d][required] | ||
|
|
||
| Options: | ||
| --install-completion Install completion for the current shell. | ||
| --show-completion Show completion for the current shell, to copy it or customize the installation. | ||
| --help Show this message and exit. | ||
|
|
||
| // Pass a date | ||
| $ python main.py 1956-01-31 | ||
|
|
||
| Interesting day to be born: 1956-01-31 | ||
| Birth week name: Tuesday | ||
|
|
||
| // An invalid date | ||
| $ python main.py july-19-1989 | ||
|
|
||
| Usage: main.py [OPTIONS] BIRTH:[%Y-%m-%d] | ||
|
|
||
| Error: Invalid value for 'BIRTH:[%Y-%m-%d]': 'july-19-1989' does not match the format '%Y-%m-%d'. | ||
| ``` | ||
|
|
||
| </div> | ||
|
|
||
| ## Custom date format | ||
|
|
||
| You can also customize the formats received for the `date` with the `formats` parameter. | ||
|
|
||
| `formats` receives a list of strings with the date formats that would be passed to <a href="https://docs.python.org/3/library/datetime.html#datetime.date.strftime" class="external-link" target="_blank">datetime.strptime()</a>. | ||
|
|
||
| For example, let's imagine that you want to accept an ISO formatted date, but for some strange reason, you also want to accept a format with: | ||
|
|
||
| * first the month | ||
| * then the day | ||
| * then the year | ||
| * separated with "`/`" | ||
|
|
||
| ...It's a crazy example, but let's say you also needed that strange format: | ||
|
|
||
| ```Python hl_lines="8" | ||
| {!../docs_src/parameter_types/date/tutorial002.py!} | ||
| ``` | ||
|
|
||
| !!! tip | ||
| Notice the last string in `formats`: `"%m/%d/%Y"`. | ||
|
|
||
| Check it: | ||
|
|
||
| <div class="termy"> | ||
|
|
||
| ```console | ||
| // ISO dates work | ||
| $ python main.py 1969-10-29 | ||
|
|
||
| Launch will be at: 1969-10-29 | ||
|
|
||
| // But the strange custom format also works | ||
| $ python main.py 10/29/1969 | ||
|
|
||
| Launch will be at: 1969-10-29 | ||
| ``` | ||
|
|
||
| </div> | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| from calendar import day_name | ||
| from datetime import date | ||
|
|
||
| import typer | ||
|
|
||
|
|
||
| def main(birth: date): | ||
| typer.echo(f"Interesting day to be born: {birth}") | ||
| typer.echo(f"Birth day name: {day_name[birth.weekday()]}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| typer.run(main) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| from datetime import date | ||
|
|
||
| import typer | ||
|
|
||
|
|
||
| def main(launch_date: date = typer.Argument(..., formats=["%Y-%m-%d", "%m/%d/%Y"])): | ||
| typer.echo(f"Launch will be at: {launch_date}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| typer.run(main) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
46 changes: 46 additions & 0 deletions
46
tests/test_tutorial/test_parameter_types/test_date/test_tutorial001.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import subprocess | ||
|
|
||
| import typer | ||
| from typer.testing import CliRunner | ||
|
|
||
| from docs_src.parameter_types.date import tutorial001 as mod | ||
|
|
||
| runner = CliRunner() | ||
|
|
||
| app = typer.Typer() | ||
| app.command()(mod.main) | ||
|
|
||
|
|
||
| def test_help(): | ||
| result = runner.invoke(app, ["--help"]) | ||
| assert result.exit_code == 0 | ||
| assert "[%Y-%m-%d]" in result.output | ||
|
|
||
|
|
||
| def test_main(): | ||
| result = runner.invoke(app, ["1956-01-31"]) | ||
| assert result.exit_code == 0 | ||
| assert "Interesting day to be born: 1956-01-31" in result.output | ||
| assert "Birth day name: Tuesday" in result.output | ||
|
|
||
|
|
||
| def test_invalid(): | ||
| result = runner.invoke(app, ["july-19-1989"]) | ||
| assert result.exit_code != 0 | ||
| # TODO: when deprecating Click 7, remove second option | ||
| assert ( | ||
| "Error: Invalid value for 'BIRTH:[%Y-%m-%d]': 'july-19-1989' does not match the format '%Y-%m-%d'" | ||
| in result.output | ||
| or "Error: Invalid value for 'BIRTH:[%Y-%m-%d]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d)" | ||
| in result.output | ||
| ) | ||
|
|
||
|
|
||
| def test_script(): | ||
| result = subprocess.run( | ||
| ["coverage", "run", mod.__file__, "--help"], | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| encoding="utf-8", | ||
| ) | ||
| assert "Usage" in result.stdout |
33 changes: 33 additions & 0 deletions
33
tests/test_tutorial/test_parameter_types/test_date/test_tutorial002.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import subprocess | ||
|
|
||
| import typer | ||
| from typer.testing import CliRunner | ||
|
|
||
| from docs_src.parameter_types.date import tutorial002 as mod | ||
|
|
||
| runner = CliRunner() | ||
|
|
||
| app = typer.Typer() | ||
| app.command()(mod.main) | ||
|
|
||
|
|
||
| def test_main(): | ||
| result = runner.invoke(app, ["1969-10-29"]) | ||
| assert result.exit_code == 0 | ||
| assert "Launch will be at: 1969-10-29" in result.output | ||
|
|
||
|
|
||
| def test_usa_weird_date_format(): | ||
| result = runner.invoke(app, ["10/29/1969"]) | ||
| assert result.exit_code == 0 | ||
| assert "Launch will be at: 1969-10-29" in result.output | ||
|
|
||
|
|
||
| def test_script(): | ||
| result = subprocess.run( | ||
| ["coverage", "run", mod.__file__, "--help"], | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| encoding="utf-8", | ||
| ) | ||
| assert "Usage" in result.stdout |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from datetime import date, datetime | ||
| from typing import Any, Optional, Sequence | ||
|
|
||
| import click | ||
|
|
||
|
|
||
| class Date(click.DateTime): | ||
| name = "date" | ||
|
|
||
| def __init__(self, formats: Optional[Sequence[str]] = None): | ||
| self.formats = formats or ["%Y-%m-%d"] | ||
|
|
||
| def _try_to_convert_date(self, value: Any, format: str) -> Optional[date]: | ||
| try: | ||
| return datetime.strptime(value, format).date() | ||
| except ValueError: | ||
| return None | ||
|
|
||
| def __repr__(self) -> str: | ||
| return "Date" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just a quick note here that if we do want to progress with this PR at some point, the docs should be updated with the new format, and using
Typer()explicitely in the tutorial examples.