作为一个简单的例子,我想使用timeitfn
函数,该函数内部有一个x
变量。因此,我将{'x': 20, 'fn': fn}
作为我的全局命名空间传递:
from timeit import timeit
def fn():
print('This line executed.')
return x
print(timeit('fn()', globals={'x': 20, 'fn': fn}, number=1_000_000))
我认为因为x
不是本地的,Python会检查全局名称空间以找到它。然后我返回"This line executed."
,后面是一个名称错误,它说:name 'x' is not defined
。但是Python会看到{'x': 20, 'fn': fn}
名称空间,因为当我删除'fn': fn
部分时,错误会变为name 'fn' is not defined
对于exec
函数也是如此(如果这有帮助或有关系):
def fn():
print('This line executed.')
return x
s = """def fn():
print('This line executed.')
return x"""
exec('fn()', {'x': 10, 'fn': fn})
如何将x
引入这些函数?它是将它们定义为模块级变量并将globals()
字典传递给global
参数的唯一选项吗
正如文件所说的^{} :
这专门解决了我的问题。因此,当Python试图在
fn
函数中查找x
时(因为它不是本地的或非本地的),它会找到定义它的位置,并查看函数在中定义的全局名称空间,而不是我们作为全局名称空间提供的全局字典虽然
{'x': 20, 'fn': fn}
是Python可以找到标签fn
的全局字典,但是fn
函数本身没有在那里定义,它在那里被称为每个模块都有自己的全局变量, 当我们说
'fn': fn
时,我们的意思是:fn
(例如answer.py
),该模块有自己的全局变量李>因此,如果在
answer.py
中没有像x
这样的全局变量,fn
无法调用它,您将得到NameError
以下是一个例子:
结果:
因此,如果您想让这些函数在全局变量中使用
x
,您可以选择以下选项:相关问题 更多 >
编程相关推荐