简体   繁体   中英

I don't quite understand this template function in Python

#template.py

import fileinput, re

field_pat = re.compile(r'\[(.+?)\]')

scope = {}

def replacement(match):
    code = match.group(1)
    try:
        return str(eval(code, scope))
    except SyntaxError:
        exec code in scope
        return

lines = []
for line in fileinput.input():
    lines.append(line)
text = ''.join(lines)

print field_pat.sub(replacement, text)

#text.py

[x = 1]
[y = 2]
The sum of [x] and [y] is [x + y]

If I execute "python template.py text.py" in command line, if will print 'The sum of 1 and 2 is 3'. In the file template.py, replacement() is a function, why it is an argument of sub() function and it does not have argument?(it's supposed to take an match object as argument) And also, what is the scope dictionary for if it is empty?? Many thanks!!!

So you are asking several questions about this code. What it is intended to do is quite clear: It is intended to

  1. read the input file,
  2. merge it into one line,
  3. For each expression in square brackets found in that line
  4. call eval(code,scope) , where code is the expression in brackets.

Now for your specific questions:

  1. replacement() is a function, why it is an argument of sub() function and it does not have argument?

Because that is how sub() function works

re. sub (pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl . If the pattern isn't found, string is returned unchanged. repl can be a string or a function ; [...] If repl is a function, it is called for every non-overlapping occurrence of pattern . The function takes a single match object argument, and returns the replacement string.

Here pattern is the self argument and repl is set to our replacement() function. It will receive the match object as an argument that contains references to each matched group.

  1. And also, what is the scope dictionary for if it is empty?

That is the dictionary that will be used to keep track of variable assignments. It will be supplied as the second argument to eval() .

For illustration here is a trace of execution of the replacement() function. The function is executed exactly 5 times.

Evaluating 'x = 1', scope = []
Evaluating 'y = 2', scope = ['x : 1']
Evaluating 'x', scope = ['x : 1', 'y : 2']
Evaluating 'y', scope = ['x : 1', 'y : 2']
Evaluating 'x + y', scope = ['x : 1', 'y : 2']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM