我想用相关字典中的值替换关键字。
文件1.py
import file2
file2.replacefunction('Some text','a_unique_key', string_variable1)
file2.replacefunction('Other text','another_unique_key', string_variable2)
file2.replacefunction('More text','unique_key_3', string_variable2)
stringvariable1
,在第一个函数调用中使用,是一个局部变量,file1.py
因此可以作为函数中的参数访问。它故意与后来在该参数位置使用的变量不同。
文件2.py
import re
keywords = {
"a_unique_key":"<b>Some text</b>",
"another_unique_key":"<b>Other text</b>",
"unique_key_3":"<b>More text</b>",
}
def replacefunction(str_to_replace, replacement_key, dynamic_source):
string_variable2 = re.sub(str_to_replace, keywords[replacement_key], dynamic_source)
return string_variable2 <-- this variable needs to be accessible
字典中的替换值keywords
比上面显示的更复杂,为了简洁起见,只是这样演示。
问题发生在第二次调用replacefunction
in file1.py
- 它无法访问stringvariable2
这是运行的第一个函数的结果。
我已经看到访问在该函数之外的函数中生成的变量的方法是执行以下操作:
def helloworld()
a = 5
return a
mynewvariable = helloworld()
print mynewvariable
5 <-- is printed
但是这种方法在这种情况下不起作用,因为函数需要在每次函数调用后更新的字符串上工作,即:
do this to string 2 # changes occur to string 2
do this to string 2 # changes occur to string 2
do this to string 2 # changes occur to string 2
我可以在没有函数的情况下实现所需的功能,但只是试图最小化代码。
有没有办法从函数外部访问变量,明确地作为变量而不是通过分配给函数?