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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With