Post #2445755
2026-04-30 00:46 UTC
And then you would use "type=date" in your parser.add_argument call to use that date function for parsing.
Of course, in the specific example of parsing a date, you could specify "type=dt.date.fromisoformat" instead.
But then parsing errors would show fromisoformat to the user:
program: error: argument date: invalid fromisoformat value: '01/01/2025'
And that's not the most user-friendly experience.
🧵 (2/3)
Replies (1)
-
@treyhunner@mastodon.social 2026-04-30 00:46
If you want to more deeply customize the message shown to the user, you can raise an argparse.ArgumentTypeError instead of a ValueError: def date(string): try: return dt.date.fromisoformat(string) except ValueError: message = "invalid YYYY-MM-DD date: {string!r}" raise argparse.ArgumentTypeError(message) from None If we had raised a ValueError, the printed message will be prefixed with "argument date: ". Not so bad, but sometimes unwanted. 🧵 (3/3)