如何以编程方式设置全局(模块)变量? [英] How to programmatically set a global (module) variable?

查看:94
本文介绍了如何以编程方式设置全局(模块)变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程的方式定义全局变量。类似于我想要做的事情会是:

$ $ $ $ code> definitions = {'a':1,'b':2, 'c':123.4}
用于definitions.items()中的定义:
exec(%s =%r%定义)#a = 1等

具体而言,我想创建一个包含可访问变量的模块 fundamentalconstants 作为 fundamentalconstants.electron_mass 等等,其中所有的值都是通过解析一个文件获得的(因此需要以编程的方式进行赋值)。



现在,上面的 exec 解决方案可以工作。但是我对它有点不安,因为我担心 exec 不是实现设置模块全局变量目标的最简单方法。

解决方案

您可以在由globals()返回的字典中设置全局变量:

 定义= {'a':1,'b':2,'c':123.4} 
用于名称,定义的值.items():
globals()[名称] =值


I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:

definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
    exec("%s = %r" % definition)  # a = 1, etc.

Specifically, I want to create a module fundamentalconstants that contains variables that can be accessed as fundamentalconstants.electron_mass, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).

Now, the exec solution above would work. But I am a little bit uneasy with it, because I'm afraid that exec is not the cleanest way to achieve the goal of setting module globals.

解决方案

You can set globals in the dictionary returned by globals():

definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
    globals()[name] = value

这篇关于如何以编程方式设置全局(模块)变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆