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.
Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
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
You question is really: how can I get Python to do floating point division by default. The answer is:
from __future__ import division
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With