Mark Harrison Mark Harrison - 7 months ago 24
Python Question

Python: eval() that coerces values to floating point?

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.

Answer

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