Home >Backend Development >Python Tutorial >Python built-in function——eval
Python built-in function - eval
eval
evaleval(expression [, globals [, locals]])
This function is used to dynamically execute an expression string, or compiled by the compile function code object.
The parameter expression is an expression string, or the name of the compiled code object;
The parameter globals is the global namespace, which can specify the scope of the global scope when executing the expression. For example, specifying certain modules can use.
If this parameter is defaulted, the current global namespace currently calling this function will be used;
The parameter locals is the local scope namespace, which is used to specify the local namespace accessed when executing the expression.
If the global namespace parameter appears, but the default built-in module is used, the module will be automatically copied to the global namespace.
It means that no matter how it is set, the built-in module can be used.
If both namespaces use the default method, the namespace when calling this function will be used to find the corresponding variable.
Why use this function?
The reason for this function should be the difference between dynamic language and compiled language.
Because it is basically impossible to dynamically generate code in compiled language,
But dynamic language can, It means that the software has been deployed to the server,
but as long as few changes are made, this part of the code has to be modified directly, and the changes can be implemented immediately without reloading the entire software.
Another one, this function can be used in machine learning.
For example, according to the frequency and method of using the software, the code can be dynamically modified to adapt to user changes.
Thinking of this, does it have the vitality ability to self-update the code and achieve improved progress?
If it does destructive actions, it is actually a virus.
>>> eval('1+1')
2
#全局命名空间为空,使用局部命名空间 >>> def make_fn(code): import math ALLOWED_LOCALS = {v:getattr(math,v) for v in filter( lambda x: x.startswith('_'),dir(math)) } return eval('lambda x: %s'%code ,None,ALLOWED_LOCALS) >>> f = make_fn('x+1') >>> print f(2)
3
#使用全局命名空间 >>> def make_fng(code): import math ALLOWED = {v:getattr(math, v) for v in filter(lambda x: not x.startswith('_'), dir(math)) } ALLOWED['__builtins__'] = None return eval('lambda x: %s' % code, ALLOWED, {}) >>> f = make_fng('cos(x)') >>> print f(9) -0.911130261885 >>> f = make_fng('cos(x*x)') >>> print f(9) 0.776685982022
The above is the Python built-in function-eval For more related content, please pay attention to the PHP Chinese website (www.php.cn)!