2014-02-08 38 views
1

我有一些存儲在.txt文件中的屬性,這些屬性被多個模塊存儲的幾個不同的類和函數使用。爲了能夠從這些不同的位置訪問屬性,我有一個空白模塊。Python對ConfigParser的使用

將模塊本身設置爲ConfigParser對象還是讀入所有參數並將它們設置爲模塊級屬性會更好嗎?

I.e.來訪問參數時,第一種方式

blank_module = ConfigParser.ConfigParser() 
blank_module.read("file.txt") 

Then access with blank_module.get('section1', 'property1') 

VS

local_var = ConfigParser.ConfigParser() 
local_var.read("file.txt") 

blank_module.property1 = local_var.get('section1', 'property1') 
blank_module.property2 = local_var.get('section1', 'property2') 
etc... 
then access with blank_module.property1 

第二種方法看起來更優雅,但我不能確定他們將如何在性能方面有所不同。

回答

1

我不認爲這是你應該擔心的表現。問題是易用性。模塊的用戶可能會發現訪問已經從文件中提取的變量而不是使用ConfigParser API會更方便。

此外,你可以做錯誤的模塊中的檢查,這樣就可以解釋讀取文件的問題:

import ConfigParser 
local_var = ConfigParser.ConfigParser() 
try: 
    local_var.read("file.txt") 
except (ConfigParser.Error, OSError) as e: 
    # Error reading 'file.txt' or something like that 

try: 
    blank_module.property1 = local_var.get('section1', 'property1') 
except ConfigParser.Error as e: 
    # Handle the error 
try: 
    blank_module.property2 = local_var.get('section1', 'property2') 
except ConfigParser.Error as e: 
    # Handle the error 
etc...