1

I have a Python script that parses inputs from the command line. One of these arguments is a string containing a list of lists (e.g. python myscript.py -b '[[0,1],[2,3],[4,5]]'). There are several ways in which I can directly convert this string into a list of lists, like json.loads() or ast.literal_eval().

It might be useful for me to be able to include NumPy values in this string, like '[[0, 2*np.pi],[-np.pi/2, np.pi/2]]' and still be able to convert this string into a list of lists. However, none of the two methods mentioned above seems to work and I couldn't find anything suitable online. Does anyone know a method that is able to handle this? I'd rather not to write a method myself if something suitable already exists.

SteRinaldi
  • 40
  • 8
  • You can use `eval()`. Also if you import `pi` directly (e.g. `from math import pi` or `from numpy import pi`), you could parse this `'[[0, 2*pi],[-pi/2, pi/2]]'`. – norok2 May 31 '22 at 09:22
  • Technically, `eval` *can* be used, but introduces security vulnerability. TBH, I’d recommend writing your own method, even if it just wraps `eval` with the view of sanity checking the statement to be evaluated. – S3DEV May 31 '22 at 09:26

1 Answers1

2

Use eval():

import numpy as np
string = '[[0, 2*np.pi],[-np.pi/2, np.pi/2]]'
eval(string)

OUTPUT:
[[0, 6.283185307179586], [-1.5707963267948966, 1.5707963267948966]]

NOTE: there are some downsides when using eval, see link.

T C Molenaar
  • 3,205
  • 1
  • 10
  • 26
  • 2
    Please attach a caveat to using `eval`, as the user *must* understand *exactly* what is being evaluated. [Reference](https://stackoverflow.com/a/1832957/6340496). Generally, `ast.literal_eval` should be used, but will not work in this case. – S3DEV May 31 '22 at 09:23