2

I"m getting a list of strings back as an argument from arg_parse, and I would like to convert some of those strings to tuples if it is easily possible.

Here is the list I'm getting from argparse:

['adding_light', '(shift_right_cv,shift_left_cv)']

I wonder how to convert this '(shift_right_cv,shift_left_cv)' to a tuple.

I don't want to use eval, as these strings will be inputted by the user (argparse arguments).

Unfortunately, ast.literal.eval() doesn' work -- I get

raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x00000000036A9BA8>
>>> 

The suggestions from these threads have been tried out ( not the complicated one):

Parse a tuple from a string?

Convert a string to a tuple

If there is no easy solution, I may just turn the tuple into a list --so I will get back a nested list from argparse, and see if that is easier to handle. I could also use RE, but I'm concerned about properly covering all cases (user input may possibly break the code).

Thank you.

Moondra
  • 4,399
  • 9
  • 46
  • 104
  • what's wrong with `tuple(my_list[optional:slice])`? – Julien Oct 31 '17 at 05:21
  • 3
    Your strings don't have quotes around them (the reason for the error). I'd recommend cleaning up each string and then tuplizing your strings yourself, instead of using `ast`. – cs95 Oct 31 '17 at 05:23
  • @Moondra If this is what you meant, you may locate those 2 consecutive list elements, and then delete the `(` from the 1st and `)` from the 2nd, and then do `thetuple = (1st, 2nd)`. Is this easy enough or else..? –  Oct 31 '17 at 05:37
  • 1
    "doesn't work" it works fine if you provide syntactically correct tuples, not sure what you expect when inputting malformed ones -- getting an exception saying they are malformed seems like very much *working* -- so either the user provided bad input or you simply forgot to massage the input to something that can be converted – jonatan Oct 31 '17 at 05:42
  • @jonatan It's not a malformed tuple -- I fixed the placement of single quotes. – Moondra Oct 31 '17 at 15:00
  • 1
    If you put `(shift_right_cv,shift_left_cv)` directly into a Python file, you would get a tuple where the first element contains whatever object the `shift_right_cv` variable points to the second element contains whatever object the `shift_left_cv` variable points to. Is that what you want? The ast` module is not capable of using local variables. You could use `eval()` if the source is trusted. – Arthur Tacca Oct 31 '17 at 15:16
  • @Moondra if you are indeed trying to evaluate variables, then you're trying to use `eval`. ast.literal_eval reads *literals*, that's what makes it safe. Also consider just splitting input on comma instead of trying to convert it into data structures (if all you're looking for is a sequence of names) and then compare the input to what you want to allow – jonatan Oct 31 '17 at 22:43

0 Answers0