Parsing boolean values with argparse

Posted in :

滿神奇的,在使用 argparse, 如果使用 bool 型別,也有使用 default value, 變成無法在參數的地方蓋過這一個 default value.

解法分為 python 3.9 以前,和 python 3.9+

I think a more canonical way to do this is via:

command --feature

and

command --no-feature

argparse supports this version nicely:

Python 3.9+:

parser.add_argument('--feature', action=argparse.BooleanOptionalAction)

Python < 3.9:

parser.add_argument('--feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

Of course, if you really want the --arg <True|False> version, you could pass ast.literal_eval as the “type”, or a user defined function …

def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
       return True
    elif 'FALSE'.startswith(ua):
       return False
    else:
       pass  #error condition maybe?

這個參數的型別就改「字串」(str)來處理,一切變的簡單點。


資料來源

Argparse optional boolean
https://stackoverflow.com/questions/52403065/argparse-optional-boolean

Parsing boolean values with argparse
https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *