Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parser.add_argument support multiple types [duplicate]

Tags:

python

parsing

I'm using my parser like so

 parser.add_argument('owner_type', type=int, required=False, location=location)

I want to be able to send both int and str in that field owner_type. is there a way to do that?

Didn't find anything in the docs.

like image 200
WebQube Avatar asked Oct 17 '25 16:10

WebQube


1 Answers

You can do something like this:

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Demo.')
    parser.add_argument('-e', dest='owner_type', help="help text")
    args = parser.parse_args()
    owner_type = args.owner_type

    if owner_type is not None and owner_type.isdigit():
        owner_type = int(owner_type)

    print(type(owner_type))

This will only work for int and strings. If you need to handle floats, then you need to handle this case differently as well.

The output:

~/Desktop$ python test.py -e 1
<type 'int'>
~/Desktop$ python test.py -e test
<type 'str'>
~/Desktop$ python test.py 
<type 'NoneType'>
like image 123
Rafael Avatar answered Oct 20 '25 07:10

Rafael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!