473,549 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

wx.Config encapsulation improved with __getattribute_ _()

bartonc
6,596 Recognized Expert Expert
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 5697
bartonc
6,596 Recognized Expert Expert
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
3616
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 purpose. This works fine if I already have an instantiation of the class, but not when I try this on the class object directly. A bare bones...
1
2305
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
6577
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 (unless called explicitely). Here is the exact citation: """ The following methods only apply to new-style classes. __getattribute__( self, name)
3
2568
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
2041
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
2507
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: x.__getattribute__('name') <==> x.name
4
3295
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 custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do...
6
3540
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: class X( object ): y = 'private value' def get_y( self ): return self.y
8
1757
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 works, but would like to take any suggestions you guys have. I've commented out the "delattr" call because it throws an AttributeError (although I...
0
7518
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7446
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7956
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7808
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5087
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3480
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.