Post #1882702
2026-04-30 00:46 UTC
Python Tip #119 (of 365):
Don't just rely on the built-in types for argparse's type parameter
You can create your own argparse "type" with a callable that accepts a string and returns the parsed object, raising a ValueError (with a user-facing message) if parsing failed.
If you wanted to accept a YYYY-MM-DD date for an argument, you could make a date function:
import datetime as dt
def date(string):
return dt.date.strptime(string, "%Y-%m-%d")
...
🧵 (1/3)
#Python #DailyPythonTip
Replies (2)
-
@treyhunner@mastodon.social 2026-04-30 00:46
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)
-
@anubhav@hachyderm.io 2026-04-30 11:09
@treyhunner@mastodon.social Thanks; last week I had been wanting this. That simple, hunh?! For the time being, did the usual (accept basic type; then do own parsing, validation after collecting the options).