gpt4 book ai didi

python - 从外部模块执行全局变量

转载 作者:行者123 更新时间:2023-11-28 21:50:28 24 4
gpt4 key购买 nike

我有一个外部模块,我想在其中将“exec”表达式设置为全局(因为我需要将字符串作为变量名传递)

所以,我有一个类似的功能

def fct_in_extern_module():
exec 'A = 42' in globals()
return None

在我的主脚本中有

import extern_module
extern_module.fct_in_extern_module()

那么,为什么我有

NameError: name 'A' is not defined

如果我这样做(在主脚本中)

def fct_in_main():
exec 'B = 42' in globals()

fct_in_main()

>>> B
42

知道如何在外部模块中将字符串“A”设置为变量名吗?

谢谢!

最佳答案

globals() 表示“this 模块的全局字典”。因此,您选择编写 extern_module.py 的方式不会影响任何其他模块的全局字典。

一种修复方法:将其定义为:

def fct_in_extern_module(where):
exec 'A = 42' in where

并将其命名为:

extern_module.fct_in_extern_module(globals())

当然,像往常一样,exec 并不是解决问题的最佳方法。更好:

def fct_in_extern_module(where):
where['A'] = 42

更快更清洁。

关于python - 从外部模块执行全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887664/

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