469,950 Members | 1,941 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Share your developer knowledge by writing an article on Bytes.

wx.Config encapsulation improved with __getattribute__()

bartonc
6,596 Expert 4TB
Still have to prepend "default" when assigning variables to this class, but it now allows val = inst.vaule:
Expand|Select|Wrap|Line Numbers
  1. """Encapuslate a Default Values Object and Config File"""
  2.  
  3. from inspect import getmembers
  4. import wx
  5.  
  6. class DefaultValueHolder(object):
  7.     """Intended for use with wxConfig (or maybe _winreg) to set up and/or get
  8.        registry key names and values. Name attrs as default*. "default"
  9.        will be stripped of when reading and writing to the config file.
  10.        You may not use the name varDict as one of the variable names."""
  11.  
  12.     def __init__(self, appName, grpName):
  13.         """Open or create the application key"""
  14.         self.appName = appName
  15.         self.grpName = grpName  # if the key or group doesn't exit, it will be created
  16.         self.config = wx.Config(appName)     # Open the file (HKCU in windows registry)
  17.  
  18.     def __getattribute__(self, name):
  19.         try:
  20.             return object.__getattribute__(self, "default%s" %name)
  21.         except AttributeError:
  22.             return object.__getattribute__(self, name)
  23.  
  24.     def GetVariables(self):
  25.         return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
  26.                 for var in getmembers(self) if var[0].startswith('default')]
  27.  
  28.     def SetVariables(self, varDict={}, **kwargs):
  29.         kwargs.update(varDict)
  30.         for name, value in kwargs.items():
  31.             setattr(self, "default%s" %name, value)
  32.  
  33.     def InitFromConfig(self):
  34.         config = self.config
  35.         group = self.grpName
  36.  
  37.         if not config.Exists(group):
  38.             self.WriteRegistryGroup(group)
  39.  
  40.         else:
  41.             config.SetPath(group)
  42.             for var in self.GetVariables():
  43.                 name = var['name']
  44.                 if config.Exists(name):
  45.                     value = self.ReadRegistry(name, var['type'])
  46.                     self.SetVariables({name:value})
  47.                 else:
  48.                     self.WriteRegistry(name, var['value'], var['type'])
  49.         config.SetPath("")
  50.  
  51.     def WriteRegistryGroup(self, group):
  52.         self.config.SetPath(group)
  53.         for var in self.GetVariables():
  54.             self.WriteRegistry(var['name'], var['value'], var['type'])
  55.         self.config.SetPath("")
  56.  
  57.     def UpdateConfig(self):
  58.         self.WriteRegistryGroup(self.grpName)
  59.  
  60.     def ReadRegistry(self, name, type):
  61.         value = None
  62.         if type == str:
  63.             value = self.config.Read(name)
  64.         elif type in (int, long):
  65.             value = self.config.ReadInt(name)
  66.         elif type == float:
  67.             value = self.config.ReadFloat(name)
  68.         return value
  69.  
  70.     def WriteRegistry(self, name, value, type):
  71.         if type == str:
  72.             self.config.Write(name, value)
  73.         elif type in (int, long):
  74.             self.config.WriteInt(name, value)
  75.         elif type == float:
  76.             self.config.WriteFloat(name, value)
  77.  
  78.  
  79. if __name__ == "__main__":
  80. ##    class SetSelfFromDefaults(object):
  81. ##        def __init__(self):
  82. ##            self.test = test = DefaultValueHolder("HETAP Pro 2.00", "Database")
  83. ##            test.SetVariables(UserName="peter", Password="pan", ServerName="MyServer", database="")
  84. ##            test.InitFromConfig()
  85. ##
  86. ##            self.SetupLoginVars(test)
  87. ##
  88. ##        def SetupLoginVars(self, defaultHolder):
  89. ##            """Cool tricks, use somewhere, someday."""
  90. ##            for var in defaultHolder.GetVariables():
  91. ##                execStr = "self.%s = %s" %(var['name'], (repr(var['value']), var['value'])[var['type'] != str])
  92. ##                exec(execStr) in locals()
  93. ##
  94. ##    testClass = SetSelfFromDefaults()
  95. ##    print testClass.UserName
  96.  
  97.     test = DefaultValueHolder("HETAP Pro 2.00", "Database")
  98.     test.SetVariables(UserName = "peter", Password = "pan", ServerName = "MyServer", database="")
  99.     test.InitFromConfig()
  100.     print test.UserName
  101.     test.defaultvar1=77
  102.     print test.GetVariables()
  103.     #### this also works:
  104.     ## test.defaultUserName = "joe"
Jan 27 '07 #1
1 5405
bartonc
6,596 Expert 4TB
I cleaned this up too:
Expand|Select|Wrap|Line Numbers
  1.  
  2.     def GetVariables(self):
  3.         return [{"name":name[7:], "value":value, "type":type(value)}
  4.                 for name, value in getmembers(self) if name.startswith('default')]
Jan 31 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Daniel Schüle | last post: by
reply views Thread by Gigi | last post: by
3 posts views Thread by Sylvain Ferriol | last post: by
5 posts views Thread by Stefan Sonnenberg-Carstens | last post: by
6 posts views Thread by Adam Donahue | last post: by
8 posts views Thread by bukzor | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.