python创建全局变量_Python从列表创建动态全局变量

I am trying to make generic config, and thus config parser. There are two config files say A and B. I want to parse sections and make global values from them according to hardcoded list.

Here is an example:

in config file:

[section]

var1 = value1

var2 = value2

In global scope:

some_global_list = [ ["var1","var2"], ["var3","var4"] ]

in function to unpack this values, by ConfigParser:

configparser = ConfigParser.RawConfigParser()

configparser.read(some_config_filename)

for variables in some_global_list:

globals()[section]=dict()

for element in configparser.items(section):

globals()[section].update({element[0]:element[1]})

This works nicely...however. Scope of globals() seem to be limited to function which is obviously not what I intended. I can access variable only while in that function.

Could someone share better yet simple idea?

I know that i might move code to main and not to worry, but I don't think it is a good idea.

I thought also about making some generator (sorry for pseudocode here):

in global scope:

for x in some_global_list:

globals()[x] = x

also tried adding this to function:

for x in some_global_list[0]:

global x

but got nowhere.

Edit :

After discussion below, here it is:

Problem solved like this:

removed whole configuration from main script to module

imported (from module import somefunction) config from module

removed globals() in fact didnt need them, since function was changed a little like so:

in function:

def somefunction:

#(...)

configparser = ConfigParser.RawConfigParser()

configparser.read(some_config_filename)

temp_list=[]

for variables in some_global_list:

tmp=dict()

for element in configparser.items(section):

tmp.update({element[0]:element[1]})

temp_list.append (tmp)

return temp_list #this is pack for one file.

now in main script

tmp=[]

for i,conf_file in enumerate([args.conf1,args.conf2,args.conf3]):

if conf_file:

try:

tmp.append([function(params...)])

except:

#handling here

#but since i needed those config names as global variables

for j,variable_set in enumerate(known_variable_names[i]):

globals()[variable_set] = tmp[i][j]

so unfortunate hack presists. But seems to work. Thx for Your help guys.

I'm accepting (if thats possible) below answer since it gave me good idea :)

解决方案

A simple way to solve this issue is in your application package within the __init__.py you can do something similar to the following:

app_config = read_config()

def read_config():

configparser = ConfigParser.RawConfigParser()

configparser.read(some_config_filename)

return configparser.as_dict() #An imaginery method which returns the vals as dict.

The "app_config" variable can be imported into any other module within the application.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值