2

I would like to evaluate symbolic expression with np array

example:

import numpy as np
a = np.array([1]*4)
b = np.array([2]*4)
res = repr(a) + ' + ' + repr(b)
value = eval(res)

error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'array' is not defined

I have a workaround but I will know if I can solve my initial problem

workaround found on stackoverflow Python eval function with numpy arrays via string input with dictionaries

formula = 'x+y'
res = eval(formula,{'x':a, 'y':b})

Edit:

in order to solve the problem add the array definition in the import module

from numpy import array
3
  • What do you want to achieve exactly? eval is evil. Commented Oct 10, 2017 at 8:53
  • When doing a copy-n-paste from a question I sometimes need to add a array=np.array to the interactive session. Commented Oct 10, 2017 at 10:09
  • @EricDuminil: i have a symbolic expression and I want a method evaluate which will apply np.array on each variable of my expression Commented Oct 10, 2017 at 16:32

1 Answer 1

2

Representations are of the form: array([1, 1, 1, 1]). So we need an array definition imported. So the following should work:

from numpy import array
a = array([1] * 4)
b = array([2] * 4)
res = repr(a) + ' + ' + repr(b)
eval(res)

Result:

array([3, 3, 3, 3])
Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot for your prompt answer, it was the same kind of answer in this link : stackoverflow.com/questions/35750639/… but I had not understood the problem with the array definition
eval is dangerous. I wonder if there's not a better way, e.g. with sympy.
I know sympy but I need the symbolic expression graph to make other more complicated stuff like Theano feature (GPU, OpenMP etc...), so I prefer to not use a whole module just to construct an expression tree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.