473,425 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,425 developers and data experts.

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

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

Similar topics

6
by: Ruud de Jong | last post by:
I have the situation where I need to construct the name of a static method, and then retrieve the corresponding function from a class object. I thought I could just use __getattribute__ for this...
1
by: Daniel Schüle | last post by:
Hello NG is this kind of usage possible for classes l = l.__getattribute__("count")(1) for example f = foo() def bar(t, m, p):
0
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called...
3
by: Sylvain Ferriol | last post by:
hello when i define __getattribute__ in a class, it is for the class instances but if i want to have a __getattribute__ for class attributes how can i do that ? sylvain
5
by: Stefan Sonnenberg-Carstens | last post by:
Hi there, I'm facing some strange things - but maybe only me is strange - anyway... i wrote the following code: +++ class T(object): def __init__(self,name='',port=80): self.name=name
5
by: Barry Kelly | last post by:
I'm running this version of Python: Python 2.4.3 (#1, May 18 2006, 07:40:45) on cygwin I read in the documentation that these two expressions are interchangeable: ...
4
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a...
6
by: Adam Donahue | last post by:
As an exercise I'm attempting to write a metaclass that causes an exception to be thrown whenever a user tries to access 'attributes' (in the traditional sense) via a direct reference. Consider:...
8
by: bukzor | last post by:
I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.