简体   繁体   中英

Python use of ConfigParser

I have some properties stored in a .txt file that are used by several different classes and functions stored over multiple modules. To be able to access the properties from these different locations I've got a blank module.

Is it better to set the module itself to be the ConfigParser object, or to read in all the parameters and set them to module level attributes?

Ie first way

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

The second way would look more elegant when coming to access the parameters, but I'm unsure how they would differ in terms of performance.

I don't think that it is performance you should worry about here. The issue is ease of use. The users of the modules would probably find it more convenient to access the variables already extracted from the file instead of using the ConfigParser API.

Further, you can do error checking in the module so that you can account for problems reading your file:

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... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM