I have a class with a long list of variables (at least a dozen). In the module I first import a constants file which contains some helper methods and all of the default constants.
from myConstants import *
class SomeClass(ParentClass):
def __init__(var1=VAR1, ..., varN=VARN):
super(SomeClass, self).init(var1, ...)
self.varM = varM
PROBLEM: I would like to be able to specify a file when I initialize the class where the file contains a subset of the constants in myConstants.py. The variables not in the init file would be loaded from the defaults. Something like:
sc = SomeClass(initFile='/path/to/file')
My thought was to have something like
from myConstants import *
from ConfigParser import SafeConfigParser
class SomeClass(ParentClass):
def __init__(var1=VAR1, ..., varN=VARN, initFile=''):
if initFile:
parser = SafeConfigParser().read(initFile)
var1 = parser('constants', 'var1') if parser('constants', 'var1') else VAR1
var2 = parser('constants', 'var2') if parser('constants', 'var2') else VAR2
....
varN = parser('constants', 'varN') if parser('constants', 'varN') else VARN
else:
var1 = VAR1
...
varN = VARN
super(SomeClass, self).init(var1, ...)
self.varM = varM
QUESTION: Is this the best way to do this? If not, what is? Seems a little long winded. I'm also not married to ConfigParser.
from foo import *, either explicitly dofrom foo import bar1, bar2, bar3, ...or alternativelyimport fooand dofoo.bar1, foo.bar2import foo, then refer to them asfoo.bar1etc - no need to change anything when you add new ones.lengthfrom the myConstants module or defined locally? WithmyConstants.lengthyou definetely know.