eval(object, global,local ) evalute valid python code
object: input object of string or code object
global: (optional ) global dictionary object
local: (optional ) local dictionary object
Using string object
my_str="x='plus2net'\nprint(x)"
eval(my_str)
Output
plus2net
Using code object
We create a code object by using compile()
cb=compile('print("Hello")', '', 'single')
eval(cb)
Output
Hello
Using restrictions
We can allow some functions in global scope only to evalute by using global option. Let us import our math module and find the sum of a iterable_object
This will generate error as we have used one empty dictionary ( not allowing any method ) .
import math
str="print(math.fsum([1,2,3,4,5]))"
eval(str,{})
This will work as we have allowed math.fsum to execute. Output is 15.0
import math
str="print(fs([1,2,3,4,5]))"
eval(str,{'fs':math.fsum}) 3 15.0
builtin functions
eval() has full access to all builtin functions of Python. This code will not generate any error though we have supplied an empty dictionary ({}) to globals.
str="print(sum([1,2,3,4,5]))"
eval(str,{}) # 15
Note that sum() is a builtin function but fsum() is included in math module.
Take precaution by not allowing un-cleaned code to get executed through exec(). There is a potential danger in allowing codes to get executed without proper check.
«All Built in Functions in Python
dir() compile() exec() repr()
← Subscribe to our YouTube Channel here