Python:将变量添加到导入函数的作用域中
考虑以下情况:Python:将变量添加到导入函数的作用域中,python,scope,Python,Scope,考虑以下情况: #module.py def test(): foo = bar+'foo' print foo if __name__ == '__main__': bar='test' test() 主文件是: #main.py import module bar = 'test' module.test() 运行main.py显然会生成namererror。我知道有几种方法可以解决这一问题(例如,在main.py中重新定义函数),但我的问题是:如何在不修
#module.py
def test():
foo = bar+'foo'
print foo
if __name__ == '__main__':
bar='test'
test()
主文件是:
#main.py
import module
bar = 'test'
module.test()
运行main.py显然会生成namererror
。我知道有几种方法可以解决这一问题(例如,在main.py中重新定义函数),但我的问题是:如何在不修改module.py代码的情况下将bar变量添加到函数范围,以及更一般地说,在这种情况下,什么是最佳做法
编辑:
使用模块导入中的*
,同样的问题如何