exec后未定义变量('Variable=value')

2024-06-06 09:53:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我被这件事缠住了。我在一个视图中使用了一个名为modifier_dico的函数,该函数位于名为函数.py. 第一行修饰符_dico如下:

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

我的看法是:

^{pr2}$

当我试图访问这个视图时,我在Django的调试页面上得到name 'dico' is not defined。在

但是当我看the local vars of modifier_dico in the traceback时,我有一个变量dico,其值为{}

看起来exec()没有像我预期的那样工作。在


Tags: thedjango函数py视图def页面修饰符
1条回答
网友
1楼 · 发布于 2024-06-06 09:53:01

您没有指定要在哪个命名空间中设置名称,因此名称是在fonctions.modifier_dico()函数的范围内设置的,而不是classer_tweet()。从^{} 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.

从链接的^{} 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()在视图函数中设置其他局部变量。你真的应该对任意名称空间使用字典。在

您可能仍然可以看到locals()字典中的更改,但由于函数在一个方向上返回实际局部变量的反射,因此该局部函数实际上在函数本身中不可用。换句话说,函数的实际局部变量被复制到locals()返回的字典中,对该字典的添加不会被复制回:

^{pr2}$

相关问题 更多 >