Overtime programmers the most laborious, to a picture to wake up the brain!
...
...
...
OK, wake up, come back to reality look at the code!!
executes a string representation of a function and provides a global variable for the function
The content of this article from the topic can be seen, is for after the analysis of Tornado template preparation, but also because of the use of the knowledge points of the ingenious, all alone with an article to introduce. Nonsense not much to say, directly on the code:
#!usr/bin/env Python#coding:utf-8 namespace = {' name ': ' Wupeiqi ', ' Data ': [18,73,84]} code = ' Def hellocute (): Return "name%s, age%d"% (Name,data[0], "" func = Compile (code, ' <string> ', "exec") exec func in Namespace re Sult = namespace[' Hellocute '] () print result
The result of this code execution is: name Wupeiqi,age 18
The above code parsing:
- Line 6th, code is a string, and the content of the string is a function body.
- Line 8th, compile the code string into function hello
- Line 10th, add the function hello to the namespace dictionary (key is Hello), and also add all of Python's built-in functions to the Namespace field (key is __builtins__), so The content in namespace is like a global variable, i.e.
name = Wupeiqidata = [18,73,84]def hellocute (): return "name%s, age%d"% (name,data[0],)
- Line 12th, execute the Hello function and copy the return value to result
- Line 14th, enter result
This code is very clever with wood, bright blind dog eyes have wood, incredibly the string into a function and also provide a global variable for the function. For this feature, it is a crucial part of the template language part of the Python web framework, because in the process of template processing, the HTML file is first read, then the HTML file is split, and then the segmented file is composed of a string representation of the function, And then it is the function that executes the string representation using the above method.
Fourth: The vernacular tornado source of stripped-off template outerwear foreplay