Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a argparse module that auto detects the data type

Is there any other python package or does argparse has the following feature I am expecting

arg_parser.add_argument("-v", "--some_data", required=True,
                        help="data id(int) or vehicle name (str) ")
input -v 123 output type(args.some_data) --> int
input -v abc output type(args.some_data) --> str
input -v a12 output type(args.some_data) --> str
like image 614
Rakshith Nt Avatar asked Jan 20 '26 09:01

Rakshith Nt


1 Answers

You could define a custom type that tries to parse an int, and if it fails, returns the string.

(I made your option an argument in this example for simplicity.)

import argparse

def int_or_str(s):
    try:
        return int(s)
    except ValueError:
        return s

parser = argparse.ArgumentParser()
parser.add_argument("x", type=int_or_str, help="int or str")
print(parser.parse_args(['123']))  # -> Namespace(x=123)
print(parser.parse_args(['hello']))  # -> Namespace(x='hello')

However, beware that int ignores leading and trailing whitespace, so for example int(' 1 ') succeeds.

print(parser.parse_args([' 1 ']))  # -> Namespace(x=1)
like image 193
wjandrea Avatar answered Jan 22 '26 22:01

wjandrea



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!