Reputation: 2003
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?
I.e. 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.
Upvotes: 1
Views: 441
Reputation: 48725
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...
Upvotes: 1