-
-
Notifications
You must be signed in to change notification settings - Fork 30.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
argparse int type does not accept scientific notation #78984
Comments
The 'argparse' module gives a parse error for integer arguments written in scientific notation. I would expect this to work, since integers can be constructed from literals in scientific notation. Example (also attached): import argparse
foo = int(1e3) # Works: foo = 1000
parser = argparse.ArgumentParser()
parser.add_argument( "--foo", type=int )
parser.parse_args( ["--foo=1e3"] )
# error: argument --foo: invalid int value: '1e3' |
I suppose desired behavior would be to accept the argument only if it can be converted to int without loss of information. |
The conversion fails because is trying to convert a string, not a float: >>> int("1e3")
*** ValueError: invalid literal for int() with base 10: '1e3' |
You can always do: import argparse
foo = int(1e3) # Works: foo = 1000
parser = argparse.ArgumentParser()
parser.add_argument( "--foo", type=lambda x: int(float(x)))
parser.parse_args( ["--foo=1e3"] ) |
The Test If you want to convert '1e3' to an integer, write your own function that handle it. Don't expect argparse or the stock int() to do it for you. More commonly people use 'type=bool', expecting it convert 'True' or 'False' strings to boolean values. But that's not what the bool() function does. To reiterate, 'type' is a function, not a desired class. Since this is not a bug, I think this should be closed. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: