Django study (Part 2)

Executes the function represented by the string and provides global variables for the function

The content of this article can be seen from the title, which is to prepare for the subsequent analysis of the tornado template.

   
#!usr/bin/env python
#coding:utf-8
  
namespace = {'name':'teddy','data':[25,73,84]}
  
code =  '''def hellocute():return  "name %s ,age %d" %(name,data[0],) '''
  
func = compile(code, '<string>', "exec")
  
exec func in namespace
  
result = namespace['hellocute']()
  
print result

The execution result of this code is : name teddy, age 25

 

Analysis of the above code:

Line 6, code is a string whose content is a function body.

Line 8, compile the code string into the function hello

Line 10, add the function hello to the namespace dictionary (key is hello), and also add all built-in functions of python to the namespace field (key is __builtins__),

In this way, the content in the namespace is like a global variable, that is, 5

name = wupeiqi
data = [18,73,84]
 
def hellocute():
    return  "name %s ,age %d" %(name,data[0])

 

    •  
       
      Line 12, executes the Hello function and copies the return value to result
    • Line 14, enter result

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325068196&siteId=291194637