gpt4 book ai didi

Python 3.4,无法访问使用 exec() 创建的变量

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:52 25 4
gpt4 key购买 nike

使用 Python 3.4 并在函数中,会出现以下代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary

print('test')
print(list(locals()))

exec('keys2 = list(' + ch0 + ')', locals())

print(list(locals()))
print(locals()['keys2'])

print('keys2:', keys2)

这是输出:

test
['dico', 'save', 'keys0', 'LOG_FILENAME', 'ch0', 'flag', 'completer', 'k', 'ans', 'keys1']
['dico', 'save', 'keys0', 'LOG_FILENAME', 'ch0', 'flag', 'completer', 'k', 'ans', 'keys1', '__builtins__', 'keys2']
['General informations', 'Experiments parameters', 'Calculated parameters']
Traceback (most recent call last):
File "/data_1/dataGestion.py", line 189, in consult_db
print('keys2:', keys2)
NameError: name 'keys2' is not defined

正如预期的那样,我们观察到在本地范围内创建了keys2变量,并且该变量包含了预期值(['一般信息','实验参数','计算参数']),似乎表明了字典由 locals() 返回。但无法访问此keys2变量(名称“keys2”未定义!!!)。为什么?

<小时/>

编辑1:我们看到 Keys2 位于本地范围内,因为在上述问题的代码中:

print(list(locals()))

print(locals()['keys2'])

返回:

['dico', 'keys0', 'save', 'k', 'ans', 'keys1', '__builtins__', 'flag', 'LOG_FILENAME', 'keys2', 'ch0', 'completer']
['General informations', 'Experiments parameters', 'Calculated parameters']

但是!!!为什么如果我将上面的代码更改为:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary
print('test')

exec('keys2 = list(' + ch0 + ')', locals())

keys2 = locals()['keys2']

print('keys2:', keys2)

keys2 变量没有被创建,我们可以看到再次引发了 NameError 异常:

Traceback (most recent call last):
File "/data_1/IRM/amigo/src/IRMAGE_python_modules/IRMAGE_dataGestion.py", line 191, in consult_db
print('keys2:', keys2)
NameError: name 'keys2' is not defined
<小时/>

编辑2:通过继续使用 exec() 和 locals() ...考虑以下代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary
print('test')

namespace = locals()

print(list(namespace))
print(list(locals()))
print(list(globals()))

exec('keys2 = list(' + ch0 + ')', namespace)

keys2 = namespace['keys2']
print()

print(list(namespace))
print(list(locals()))
print(list(globals()))

print('keys2:', keys2)

输出为:

test
['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME']
['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace']
['__spec__', 'nbLigne', 'remove', 'listdir', 'getSampleStyleSheet', 'Paragraph', '__builtins__', 'system', 'upvivification', '__package__', 'exit', '__doc__', 'AutoVivification', 'recupParameter', 'verSofts', 'logging', 'revivification', 'renameComment', 'unvivification', 'creatExpParameter', 'rlcompleter', 'consult_db', 'makedirs', 'datetime', 'isdir', 'recupCover', 'MyCompleter', 'verifFichier', 'dico2txt', 'para2dic', 'readlineComp', '__name__', '__file__', 'anonym', '__cached__', '__loader__']

['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace', '__builtins__', 'keys2']
['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace', '__builtins__', 'keys2']
['__spec__', 'nbLigne', 'remove', 'listdir', 'getSampleStyleSheet', 'Paragraph', '__builtins__', 'system', 'upvivification', '__package__', 'exit', '__doc__', 'AutoVivification', 'recupParameter', 'verSofts', 'logging', 'revivification', 'renameComment', 'unvivification', 'creatExpParameter', 'rlcompleter', 'consult_db', 'makedirs', 'datetime', 'isdir', 'recupCover', 'MyCompleter', 'verifFichier', 'dico2txt', 'para2dic', 'readlineComp', '__name__', '__file__', 'anonym', '__cached__', '__loader__']
keys2: ['Calculated parameters', 'General informations', 'Experiments parameters']

通过这个结果,我了解到作为 exec() 参数传递的字典(命名空间)用于查找函数 exec() 范围内的变量,而且该字典(命名空间)也包含之后创建的所有变量exec() 的执行。这是可以理解的,但我还不明白为什么在编辑1中,keys2 = locals()['keys2']不起作用,而keys2 = namespace['keys2']在此编辑2中起作用?

<小时/>

编辑3:通过继续使用 exec() 和 locals() ...考虑以下代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary
print('test')

print(list(locals()))
print(list(globals()))

exec("global keys2; keys2 = list(" + ch0 + "); print('\\n** keys2 inside exec function: {}'.format(keys2))", locals())

print()

print(list(locals()))
print(list(globals()))

print('keys2:', keys2)

输出为:

test
['ch0', 'LOG_FILENAME', 'k', 'flag', 'save', 'ans', 'keys0', 'dico', 'completer', 'keys1']
['recupCover', 'MyCompleter', '__name__', 'para2dic', 'readlineComp', 'upvivification', 'listdir', 'verifFichier', 'recupParameter', 'system', 'remove', '__doc__', 'nbLigne', 'renameComment', '__spec__', '__file__', 'anonym', 'creatExpParameter', '__package__', 'isdir', 'revivification', 'exit', '__loader__', 'makedirs', 'datetime', 'consult_db', 'Paragraph', '__cached__', '__builtins__', 'AutoVivification', 'getSampleStyleSheet', 'unvivification', 'rlcompleter', 'logging', 'verSofts', 'dico2txt']

** keys2 inside exec function: ['Experiments parameters', 'Calculated parameters', 'General informations']

['ch0', 'LOG_FILENAME', 'k', 'flag', 'save', 'ans', 'keys0', 'dico', 'completer', 'keys1', '__builtins__', 'keys2']
['recupCover', 'MyCompleter', '__name__', 'para2dic', 'readlineComp', 'upvivification', 'listdir', 'verifFichier', 'recupParameter', 'system', 'remove', '__doc__', 'nbLigne', 'renameComment', '__spec__', '__file__', 'anonym', 'creatExpParameter', '__package__', 'isdir', 'revivification', 'exit', '__loader__', 'makedirs', 'datetime', 'consult_db', 'Paragraph', '__cached__', '__builtins__', 'AutoVivification', 'getSampleStyleSheet', 'unvivification', 'rlcompleter', 'logging', 'verSofts', 'dico2txt']
Traceback (most recent call last):
File "/data_1/IRM/amigo/src/IRMAGE_python_modules/IRMAGE_dataGestion.py", line 206, in consult_db
print('keys2:', keys2)
NameError: name 'keys2' is not defined

所以...即使我们在 exec() 函数中将keys2定义为全局变量,它也不在全局范围内,因为在 exec() 函数之后返回 globals() ...我承认有些事情想念我...

最佳答案

exec documentation for Python 3 中所述:

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.

您无法在 Python 3 上使用 exec 创建新的局部变量。局部变量查找完全忽略该尝试。

关于Python 3.4,无法访问使用 exec() 创建的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796024/

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