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

标签 python django python-3.x

我对这个很着迷^^。我有一个 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/

相关文章:

django - 使用 django-allauth 找不到页面(404)

python - 如何在 views.py 中检查用户的权限?

linux - SSH 使用 python 脚本

python - 如何将数据框的列修改为值

python - 将数据库中的日期值与日期文字进行比较

python - 从日期选择器获取可用性

javascript - 将两个列表转换为 X 和 Y 格式的字典

python - 从 video_ids 列表中获取 YouTube 转录数据

python - 如何加快我的代码在 NLP 问题中清理文档的速度

python - 新列中的部分字符串切片(或字符串拆分?)