There is a line containing a mathematical expression of the form:

1/3+2/3 

Is there a module that computes the value of such expressions?

3 answers 3

You can use eval

 eval('1/3+2/3') 

here you can read https://docs.python.org/3/library/functions.html#eval

But usually with such functions there are security problems in case you get a string from outside (user input for example)

    From a security point of view (as @Batanichek already said - with eval() you need to be very careful), performance and flexibility are better to use numexpr :

     In [6]: import numexpr as ne In [7]: ne.evaluate('1/3+2/3') Out[7]: array(1.0) In [8]: var1=10 In [9]: var2=2 In [10]: ne.evaluate('var1**var2') Out[10]: array(100, dtype=int32) 

    It is, by the way, faster for more complex calculations, supports the use of variables, supports NumPy, SciPy, etc.

    Numexpr supports multi-threaded computing (using all available processor cores) and VML ΠΎΡ‚ Intel (Vector Math Library, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ ΠΈΠ½Ρ‚Π΅Π³Ρ€ΠΈΡ€ΠΎΠ²Π°Π½ Π² интСловский ΠΆΠ΅ Math Kernel Library (MKL)) .

    An example of working with a regular ("Vanilla Python") array:

     In [45]: lst = [1, 2.718281828] In [46]: ne.evaluate('log(lst)') Out[46]: array([ 0., 1.]) 

    with a numpy array:

     In [50]: a = np.array([1, 2.718281828]) In [51]: ne.evaluate('log(a)') Out[51]: array([ 0., 1.]) 

    Performance comparison with NumPy for an array consisting of 1 million elements of type numpy.float64 :

     In [36]: a = np.random.rand(10**6) In [37]: a.shape Out[37]: (1000000,) In [38]: len(a) Out[38]: 1000000 In [39]: %timeit np.log(a) 10 loops, best of 3: 24.3 ms per loop In [40]: %timeit ne.evaluate('log(a)') 100 loops, best of 3: 5.45 ms per loop In [41]: %timeit np.sqrt(np.sin(a)**2 + np.cos(a)**2) 10 loops, best of 3: 84.5 ms per loop In [42]: %timeit ne.evaluate('sqrt(sin(a)**2 + cos(a)**2)') 100 loops, best of 3: 6.32 ms per loop 

      It seems like it is considered a safe analogue of eval

       import ast try: print(ast.literal_eval(1/3+2/3)) except ValueError as err: print(err) 

      Only here with this expression gives an error

      • Safely evaluate an expression or a string containing a Python expression. Pass the string and not the result of the addition. - mkkik
      • By the way, @mkkik is really curious: `ast.literal_eval ('1 + 1')` works, and ast.literal_eval('1*1') throws an exception. - Alex Titov
      • "It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing." Can it be difficult for him to do such calculations? :) - Shihkauskas
      • 1- string must be transferred 2- with literal_eval () arithmetic expressions is not intended to work. Here's how you can use ast to compute an arithmetic expression - jfs