I’ve looked around, and did not find any information to create numpy.float64 using the built-in eval function.
What I’d like is going from something like:
In [1]: x = eval("1.0")
In [2]: type(x)
Out[2]: <type 'float'>
to:
In [1]: x = eval("1.0")
In [2]: type(x)
Out[2]: <type 'numpy.float64'>
The real problem is a bit worse than just the simple example above because the argument passed to eval is most often a dictionary with many keys and values. So it would not be possible to use something like: numpy.float64("1.0").
To give you concrete real data I’m working with, here is how a string could look like (it is read from a file):
data_str = '{"var_x": {"value": 1.23, "error": 0.25, "unit": "unit name"},
"var_y": {"value": 1e+4, "error": 1.3e1, "log": False},
"var_z": ["a", {"x":1, "y":2}, (1, 2, 3), None]'
data = eval(data_str)
And then, I’d like type(data["var_x"]["value"]) returns <type 'numpy.float64'>
Do you guys have any suggestions. Did I miss an obvious method?
EDIT
The precision of numbers I will deal with in data_str will not be much more than 15-16 digits.
So converting string to float or numpy.float64 does not matter a lot for that purpose only. However these values will be passed to some complex functions, multiplied, divided… therefore to avoid any error propagation, I have to work with numpy.float64.
One workaround could be to convert (after eval) any float to numpy.float64, but it would be nice to have a direct interpretation using eval.
EDIT #2
I’m wondering why this does not work:
In [1]: import numpy as np
In [2]: x = eval("1.4", {"__builtins__":None, "np":np}, {"float":np.float64})
In [3]: type(x)
Out[3]: <type 'float'>
I thought by defining “__builtins__” to None within eval globals would avoid it to load default definition for float, which I redefine within the locals… It seems it is impossible to take out (or replace for this matter) builtin types from eval namespace (like float, int…). Any light on this is welcome 🙂
What you could do is replicate what
ast.literal_eval()does, but instead of just executing the AST you could inject calls to thenumpy.float64constructor first.