Issue34803
Created on 2018-09-25 22:31 by jessehostetler, last changed 2018-09-27 16:56 by paul.j3. This issue is now closed.
| Files | ||||
|---|---|---|---|---|
| File name | Uploaded | Description | Edit | |
| argparse-int-scientific.py | jessehostetler, 2018-09-25 22:31 | Code example | ||
| Messages (5) | |||
|---|---|---|---|
| msg326409 - (view) | Author: Jesse Hostetler (jessehostetler) | Date: 2018-09-25 22:31 | |
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' |
|||
| msg326410 - (view) | Author: Jesse Hostetler (jessehostetler) | Date: 2018-09-25 22:37 | |
I suppose desired behavior would be to accept the argument only if it can be converted to int without loss of information. |
|||
| msg326413 - (view) | Author: Pablo Galindo Salgado (pablogsal) * | Date: 2018-09-25 23:34 | |
The conversion fails because is trying to convert a string, not a float:
>>> int("1e3")
*** ValueError: invalid literal for int() with base 10: '1e3'
|
|||
| msg326414 - (view) | Author: Pablo Galindo Salgado (pablogsal) * | Date: 2018-09-25 23:36 | |
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"] ) |
|||
| msg326520 - (view) | Author: paul j3 (paul.j3) * | Date: 2018-09-27 03:35 | |
The `type` parameter is normally a function (or more generally a callable). When given a string it should convert it as needed, or raise an error. In your example that function is the stock, 'int()'.
Test `int('123')`, `int('1e3')` etc for yourself to see what it can handle.
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.
|
|||
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2018-09-27 16:56:48 | paul.j3 | set | status: open -> closed resolution: not a bug stage: resolved |
| 2018-09-27 03:35:49 | paul.j3 | set | nosy:
+ paul.j3 messages: + msg326520 |
| 2018-09-26 01:54:34 | xtreak | set | nosy:
+ xtreak |
| 2018-09-25 23:36:05 | pablogsal | set | messages: + msg326414 |
| 2018-09-25 23:34:25 | pablogsal | set | nosy:
+ pablogsal messages: + msg326413 |
| 2018-09-25 22:37:22 | jessehostetler | set | messages: + msg326410 |
| 2018-09-25 22:31:02 | jessehostetler | create | |