For those of you who have never used the *listofargs and **dictofargs syntax, here is a look at the latter. By using **kwargs, a dictionary of any size is sent into the fuction as dict(a=1, b=2). Inside the function, it's just a dictionary named kwargs (or whaterver, but this is conventional). The truly amazing thing to me is that I am able to write to the Windows registry with so little interface!
Code:
"""Encapuslate a Default Values Object and Config File"""
from inspect import getmembers
import wx
class DefaultValueHolder(object):
"""Intended for use with wxConfig (or maybe _winreg) to set up and/or get
registry key names and values. Name attrs as default*. "default"
will be stripped of when reading and writing to the config file"""
## defaultTestStr = "this is a test"
## defaultTestInt = 1
def __init__(self, appName, grpName):
"""The name of the config file that will be created"""
self.appName = appName # if the key doesn't exit, it will be created
self.grpName = grpName # same goes for groups.
self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
def GetVariables(self):
return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
for var in getmembers(self) if var[0].startswith('default')]
def SetVariables(self, **kwargs):
for name, value in kwargs.items():
setattr(self, "default" + name, value)
def InitFromConfig(self):
self.config.SetPath(self.grpName)
for var in self.GetVariables():
if var['type'] == str:
self.config.Write(var['name'], var['value'])
elif var['type'] == int:
self.config.WriteInt(var['name'], var['value'])
elif var['type'] == float:
self.config.WriteFloat(var['name'], var['value'])
if __name__ == "__main__":
test = DefaultValueHolder("MyAppName", "Database")
test.SetVariables(UserName = "joe", Password = "", ServerName = "MyServer")
#### this also works:
## test.defaultUserName = "joe"
test.InitFromConfig()
Comment