3

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.

WebQube
  • 8,510
  • 12
  • 51
  • 93

2 Answers2

1

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'>
Rafael
  • 7,002
  • 5
  • 43
  • 52
0

I don't thing that's possible. but what do you want to do ? can't you pass a string and then after do a

try:
 owner_type=int(args.owner_type)
 #it's a int
except:
 owner_type = args.owner_type
 #it's a string
p.deman
  • 584
  • 2
  • 10
  • 24