Skip to content

Instantly share code, notes, and snippets.

@EBNull
Created April 4, 2012 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EBNull/2304391 to your computer and use it in GitHub Desktop.
Save EBNull/2304391 to your computer and use it in GitHub Desktop.
Wrap a QSettings object with a more pythonic attribute based paradigm
from PyQt4 import QtCore
from config import get_data_path
class SettingsWrapper(object):
"""Wrapper for QSettings using attribute access with conversion functions"""
_known_settings = {
#'setting': (conversionFuncRead, conversionFuncReadAttr, default),
}
def __init__(self, settings, subtree=None):
self._settings = settings
self._subtree = subtree
def __repr__(self):
return "<%s wrapping %s with subtree %s>"%(self.__class__, self._settings, self._subtree)
def rewrite_settings(self):
"""Writes out the complete reparsed settings file"""
if self._subtree:
raise Exception("May only be called on main settings object")
for setting in self._known_settings:
section, name = setting.split('/')
sec = getattr(self, section)
setattr(sec, name, getattr(sec, name))
def __getattr__(self, name):
if self._subtree is None:
#Top level, need to return a wrapper for child
return self.__class__(self._settings, name + '/')
fullname = self._subtree + name
raw = self._settings.value(fullname, None)
if raw.isNull():
if fullname in self._known_settings:
return self._known_settings[fullname][2] #Default
return None
if fullname in self._known_settings:
return self._known_settings[fullname][0](getattr(raw, self._known_settings[fullname][1])())
return unicode(raw.toString()) #By default, return strings
def __setattr__(self, name, value):
if name.startswith('_'):
return super(SettingsWrapper, self).__setattr__(name, value)
if self._subtree is None:
raise ValueError("You cannot set an attribute outside of a section")
fullname = self._subtree + name
self._settings.setValue(fullname, value)
class SampleSettingsWrapper(SettingsWrapper):
_known_settings = {
'main/examplestr': (unicode, 'toString', 'default.db'),
'main/somebool': (bool, 'toBool', False),
'ab/cd': (bool, 'toBool', False),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment