Home > database >  How to define argparse default argument choices and "wildcard", dynamic choice that needs
How to define argparse default argument choices and "wildcard", dynamic choice that needs

Time:03-27

I'm currently building a command line interface in Python 3 with the argparse module.

I have a situation where I need to define choices (e.g. "today", "yesterday", "week", ...) for an optional argparse argument -s of a subparser, but also allow a date string, but only if it can be successfully parsed as datetime.datetime with a predefined format (e.g. "%Y-%m-%d"), otherwise an exception would be raised.

parser.add_argument(
            "-s",
            "--start-date",
            type=str,
            default="today",
            choices=["today", "yesterday", "week", <date>],  # date should be accepted only if datetime.strptime(date, "%Y-%m-%d") is successful
            help="start date help",
        )

Is this somehow possible?

CodePudding user response:

From my previous question, I believe this will suffice you, the custom function that validates your input. If it is the base case with today, yesterday, week, you return the strung, otherwise you try to parse the date object.

You can change it however you see fit, but this illustrates your need.

import argparse

def parse_date(s):
    if s.lower() in ["today", "yesterday", "week"]:
        return s
    
    return datetime.datetime.strptime(s, "%Y-%m-%d")

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
            "-s",
            "--start-date",
            type=lambda s: parse_date(s),
            default="today",
            help="start date help",
        )

CodePudding user response:

I'd suggest you to check this answer. This way, you could define a custom function validating your date. If the format is invalid, you just have to raise an Error inside the function and it'll be handled by argparse.

  • Related