Skip to content

Instantly share code, notes, and snippets.

@fuzzy
Created October 12, 2011 03:34
Show Gist options
  • Save fuzzy/1280195 to your computer and use it in GitHub Desktop.
Save fuzzy/1280195 to your computer and use it in GitHub Desktop.
static object with type checking, and some slight example usage.
class StaticObject(object):
'''
Class: StaticObject(object)
Author: Mike "Fuzzy" Partin
TODO:
'''
def __setattr__(self, key, val):
'''
Method: StaticObject.__setattr__(key, val)
Author: Mike "Fuzzy" Partin
TODO:
NOTE:
This only serves to ensure that our object is essentially static
No new attributes can be added, because checking for a non-existing
attribute will raise an AttributeError, and break us out to raise
UnknownAttribute. In addition strict type checking is preformed, no
deviation will be tolerated.
'''
try:
tmp = object.__getattr__(self, key)
if type(tmp) == type(val):
object.__setattr__(self, key, val)
else:
raise InvalidArgument, 'Attempt was made to change the type of an attribute. OLD: %s, NEW: %s' % (
repr(type(tmp)), repr(type(val)))
except AttributeError:
raise UnknownAttribute, 'Attempt was made to set an unknown attribute in a static object.'
class Screen(StaticObject):
'''
Class: Screen(StaticObject)
Author: Mike "Fuzzy" Partin
TODO:
'''
runTime = 0
timeStamp = time.ctime()
loadAvg = avgs = open("/proc/loadavg").readline().split()[:3]
statusMsg = ''
currProgress = 0
totalProgress = 0
output = []
__screens = {}
__masterQueue = Queue.Queue()
__masterLock = Lock()
def __setattr__(self, key, val):
StaticObject.__setattr__(self, key, val)
self.__queue.put(self)
@fuzzy
Copy link
Author

fuzzy commented Oct 12, 2011

BTW, UnknownAttribute and InvalidArgument are customized exceptions I have elsewhere in code, those can easily be changed to whatever you like obviously.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment