5

I have the following script:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-s",metavar="",help="some help",type=int,default=0.5)
print parser.parse_args()

The 3rd line, I'd like to have the type of int and string. So the user can use one of these values [0, 0.1, 0.2, 0.3, 0.5, 'best'].

How can I do that?

1
  • why not just take in a string and try casts Commented Dec 4, 2015 at 3:22

1 Answer 1

8

The type argument can be considered as a convert function instead of data type.

So you can add a converter like this:

def int_or_str(value):
    try:
        return int(value)
    except:
        return value

and pass as type.

Sign up to request clarification or add additional context in comments.

6 Comments

what do you mean pass as 'type'. If I do it your way, what value should I give to type?
@neversaint type=int_ot_str
@neversaint I just put my code on top of your code and replace type=int as type=int_ot_str, it works.
running example in ipython, please. I got NameError: global name 'in_ot_str' is not defined.
@eph The question actually includes 0.3 which is a float not an int.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.