4

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.

0

2 Answers 2

2

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'>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.