您可以通过执行以下操作从函数中设置模块级变量:
import sys
def read(filename):
module = sys.modules[__name__]
setattr(module, 'fn', filename)
return open(filename, 'r').read()
然而,这是一个非常奇怪的必要性。考虑改变你的架构。
UPD:让我们考虑一个例子:
# module1
# uncomment it to fix NameError and AttributeError
# some_var = ''
def foo(val):
global some_var
some_var = val
# module2
from module1 import *
print(some_var) # raises NameError: name 'some_var' is not defined
foo('bar')
print(some_var) # still raises NameError: name 'some_var' is not defined
# module3
import module1
print(module1.some_var) # raises AttributeError: 'module' object has no attribute 'some_var'
foo('bar')
print(module1.some_var) # prints 'bar' even without some_var = '' definition in the module1
global
因此,在导入过程中的行为方式并不那么明显。我认为,在通话setattr(module, 'attr_name', value)
期间手动执行read()
更清楚。