Python
Eval() Function
The eval()
function in python evaluates any python statement. The 1st argument
to eval function must be a string , bytes or code object.
Example 1: Python Code below
>>> variable = ‘5+(6/3)’
>>> eval(variable)
7.0 à Result
If you
directly pass a statement to eval() function it won’t execute and throws below
error.
>>>
eval(5+(6/3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: eval() arg 1 must be a
string, bytes or code object
If you
quote the input statement, then it works.
>>> eval('5+(6/3)')
7.0 à Result
The
complete Syntax of eval() function is given below. Where parameter 2nd
& 3rd are optional.
eval(expression, globals,
locals)
expression:
A string, bytes or code object.
globals: A
dictionary referring global methods & Variable.
locals: A
dictionary referring local methods & Variable.
When we use
eval() function without 2nd & 3rd parameter, the
application is executed in current scope and the available methods and variable
to the program can be checked using below code:
>>> eval(‘dir()’)
Output : ['__annotations__', '__builtins__',
'__doc__', '__loader__', '__name__', '__package__', '__spec__']
To see the
available methods & variable in globals & locals dictionary run below
commands:
>>>
eval('globals()')
>>>
eval('locals()')
Example 2: I am creating my
own function and a variable here. Now globals() & locals() have my function
and variable in it as it is running in current context. Since output is dictionary, it is embraced by
curly braces.
>>> def myfunction():
...
print('This is my function')
...
>>> myvar = 123
>>> globals()
{'__name__': '__main__', '__doc__': None,
'__package__': None,'__loader__': <class
'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__':
{}, '__builtins__': <module 'builtins' (built-in)>, 'myfunction':
<function myfunction at 0x7f3659ddab00>, 'myvar': 123}
>>> locals()
{'__name__': '__main__', '__doc__': None,
'__package__': None,'__loader__': <class
'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__':
{}, '__builtins__': <module 'builtins' (built-in)>, 'myfunction':
<function myfunction at 0x7f3659ddab00>, 'myvar': 123}
You can
also restrict the method available to statement in eval() first parameters by
explicitly mentioning them.
>>> from math import *
>>> eval('dir()') àReturns all from dir and math.
['__annotations__', '__builtins__', '__doc__',
'__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh',
'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',
'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite',
'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'tau', 'trunc']
>>> eval('dir()',{'sin':sin}) à Here in explicitly defining to have Sin method available
only.
['__builtins__', 'sin']
Example 3: In Below code I am
import math library but I in my eval() I am only making Sin function to be
available to expression.So it throwing error .
>>> from math import *
>>> a=5
>>> eval('sqrt(a)')
2.23606797749979
>>> eval('sqrt(a)',{'sin':sin})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'sqrt' is not defined
No comments:
Post a Comment