TypeError: __init__() got an unexpected keyword argument 'type' in argparse

后端 未结 2 840
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 00:28

Hey so I\'m using argparse to try and generate a quarterly report. This is what the code looks like:

parser  = argparse.ArgumentParser()

parser.add_argument(\'-         


        
2条回答
  •  梦谈多话
    2021-02-05 01:07

    The argparse documentation is not as detailed as it could be (but still has more information than many users can absorb).

    In particular, the actual information that an argument needs varies with action.

    parser.add_argument('-q', "--quarter",  action='store_true', type=int, help="Enter a Quarter number: 1,2,3, or 4 ")
    

    A store_true action does not take any parameters (i.e. nargs=0). It's default value is False, and if used the attribute is set to True.

    If you want the user to give one of those four numbers I'd suggest using

    parser.add_argument('-q', '--quarter', type=int, choices=[1,2,3,4], help="...")
    

    https://docs.python.org/3/library/argparse.html#choices has a similar example.

    The examples in https://docs.python.org/3/library/argparse.html#action give a pretty good idea of what parameters each action class takes.

    There is a Python bug/issue discussing improving either the documentation, or the error message when unnecessary parameters are given in the function. As it stands, it's the Python subclass definition that is issuing the error message.

提交回复
热议问题