Inspired by:
Convert hex string to int in Python
I tried
In [471]: parser=argparse.ArgumentParser()
In [472]: parser.add_argument('ahex',type=lambda x: hex(int(x,0)))
In [473]: parser.parse_args(['0x21c']) # valid hex string input
Out[473]: Namespace(ahex='0x21c')
In [474]: parser.parse_args(['21']) # converts valid int to hex string
Out[474]: Namespace(ahex='0x15')
In [475]: parser.parse_args(['21c']) # error if string is not valid hex
usage: ipython3 [-h] ahex
ipython3: error: argument ahex: invalid <lambda> value: '21c'
As @mgilson stressed in the comments, the type
parameter is a function, one that takes a string and returns something. It also raises an error if the string is not 'valid'. hex()
does not work as type
, because it takes an integer and returns a hex string. hex('0x21c')
is not valid use of that function.
For this quick-n-dirty solution I used a lambda
function. It could just as well been a def
. I used int(x,0)
to convert the string to a int, in a way that handles both hex strings and integer strings. Then I converted that integer back to a string using the hex
function.
So the net effect of my lambda
is to just validate the hex string. If a valid string it just returns the same thing (same as if type
was the default identity lambda x: x
).
Confusion over the nature of the type
parameter arises most often when people want a boolean
value. bool()
does not take a string like 'True' or 'False' and return a boolean value. Look up those SO questions if the issue is still confusing.