8

Is there a way to execute an eval-like function that coerces its values to floating point? I am hoping to

eval('1/3')

and have it return the floating point value .333333 rather than the integer value 0.

Mark Harrison
  • 297,451
  • 125
  • 333
  • 465

5 Answers5

14

Grab the compiler flag for __future__.division, pass it and your code to compile(), then run eval() on the returned code object.

(note by mh) This has the added advantage of not changing the division operation globally, which might have unexpected side effects. (end note)

>>> import __future__
>>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))
0.33333333333333331
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

You question is really: how can I get Python to do floating point division by default. The answer is:

from __future__ import division
kindall
  • 178,883
  • 35
  • 278
  • 309
  • actually no, I would if possible turn it on just for the evaluation of the entered expression. But, not being able to do that, this will work just fine. Thanks! – Mark Harrison Feb 23 '12 at 08:12
  • The `__future__` settings are per-module so you could do it in a separate module, but Ignacio's way is better. – kindall Jan 30 '16 at 00:50
3

The problem is there is no float value in expression.

try this eval('1/3.0')

Nilesh
  • 20,521
  • 16
  • 92
  • 148
3

This works by default on Python3

Python 3.2 (r32:88445, Dec  8 2011, 15:26:51) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333

For Python2 you can pass -Qnew on the command line (which is equivalent to from __future__ import division

$ python -Qnew
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Based on Lafada's answer, if you're getting the input string from a variable:

>>> string = '1/3'
>>> print eval(string+'.0')
0.333333333333
Knowbody
  • 66
  • 5
  • Would fail on expressions such as `string = (1/3)`. – Dilawar Jun 13 '16 at 06:48
  • The expression `string=(1/3)` doesn't create a string. It calculates 1/3, produces an integer result of 0, then stores the result in a variable called string. So then eval(string+'.0') will be trying to concatenate integer zero with string `'.0'`. It will work if your input is an actual string that hasn't been evaluated to an integer beforehand. – Knowbody Jul 18 '16 at 04:49