My requirement is to pass a tuple as command line argument like
--data (1,2,3,4)
I tried to use the argparse
module, but if I pass like this it is receiving as the string '(1,2,3,4)'
. I tried by giving type=tuple
for argparse.add_argument
, but is of no use here.
Do I have to add a new type class and pass that to type argument of add_argument
?
Update
I tried the ast.literal_eval
based on answers. Thanks for that. But it is giving spaces in the result as shown below.
(1,2,3,4)
<type 'str'>
(1, 2, 3, 4)
<type 'tuple'>
ast.literal_eval
would be an appropriatetype
parameter – Strunkargparse
docs,type
must be a function (callable
) that takes a simple string and converts it to the desired object.tuple('(1,2)')
takes a string, but splits into characters, e.g.('(', '1', ',', '2', ')')
. Also beware of your users giving you--data (1, 2, 3,4)
. The shell splits on whitespace. – Alben'(1,2)'
, but does not address theargparse
side of the question. – Albenjson.loads
to parse strings that look like dicts and lists (but not tuples). – Albeneval()
to convert it to a tuple. – Scrogan