gpt4 book ai didi

python - 变量未在 exec ('variable = value' 后定义)

转载 作者:行者123 更新时间:2023-12-03 16:57:16 25 4
gpt4 key购买 nike

我对这个很着迷^^。我有一个 View ,其中我使用了一个名为 modifier_dico 的函数,该函数位于一个名为 fonctions.py 的文件中。 modifier_dico 的前 2 行如下:

def modifier_dico(tweet,nom_dico, dico_cat):
exec('dico= {}')

我的观点如下:
def classer_tweet(request):
modifier_dico(tweet.text,"dico_status.txt", {})

当我尝试访问此 View 时,我收到 name 'dico' is not defined在 Django 的调试页面上。

但是当我看 the local vars of modifier_dico in the traceback , 我有变量 dico {}

它看起来像 exec()没有按我的预期工作。

最佳答案

您没有指定在哪个命名空间中设置名称,因此名称设置在 fonctions.modifier_dico() 的范围内。功能,而不是 classer_tweet() .来自 exec() function documentation :

In all cases, if the optional parts are omitted, the code is executed in the current scope.



您必须传入不同的字典才能将名称设置为第二个参数:
exec('dico = {}', namespace)

您不能使用 exec()在函数中设置局部变量,除非在给定函数中已经分配了名称。由于对如何访问函数中的本地命名空间进行了优化,这是一个硬性限制。来自同一文档:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.



并来自链接 locals() function documentation :

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.



因此,您不能使用 exec()在您的 View 函数中设置额外的局部变量。无论如何,您确实应该将字典用于任意命名空间。

您可能仍会看到 locals() 中的更改字典,但是因为该函数返回一个方向上实际局部变量的反射,该局部变量在函数本身中实际上并不可用。换句话说,函数的实际局部变量被复制到 locals() 的字典中。返回,该字典的添加内容不会被复制回:
>>> def no_local_foo():
... exec('foo = "bar"')
... print(locals())
... foo
...
>>> no_local_foo()
{'foo': 'bar'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in no_local_foo
NameError: name 'foo' is not defined

关于python - 变量未在 exec ('variable = value' 后定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com