Mark Harrison Mark Harrison - 1 year ago 76
Python Question

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

Is there a way to execute an

-like function that coerces its values to floating point? I am hoping to


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

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download