Help Create Good Data Model

mwt michaeltaft at gmail.com
Sat Mar 11 20:59:43 CET 2006


Hi. I'm reworking a little app I wrote, in order to separate the data
from the UI. As a start, I wanted to create a iron-clad data recepticle
that will hold all the important values, and stand up to being queried
by various sources, perhaps concurrently. In all likelihood, the app
will never need anything that robust, but I want to learn to write it
anyway, as an exercise. So here is my code. It's really simple, and I'm
sure you can see my Java background. Are there any problems here?
Something I'm missing or screwing up? I welcome any and alll feedback,
especially if it includes the *why's.* Thanks!

#!/usr/bin/python
# author mwt
# Mar '06

import copy, threading

class FAHData(object):
    """The data model for the F at H monitor."""

    def __init__(self):
        self.data = {}#this dict will hold all data
        self.mutex = threading.RLock()

    def get_all_data(self):
        """Returns a COPY of entire data dict."""
        #not sure deepcopy() is really necessary here
        #but using it for now
        #might cause some weird synchronization problems...
        try:
            self.mutex.acquire()
            return copy.deepcopy(self.data)
        finally:
            self.mutex.release()

    def get_data(self, key):
        """Returns a COPY of <key> data element."""
        try:
            self.mutex.acquire()
            return copy.deepcopy(self.data[key])
        finally:
            self.mutex.release()

    def set_value(self, key, value):
        """Sets value of <key> data element."""
        try:
            self.mutex.acquire()
            self.data[key] = value
        finally:
            self.mutex.release()

    def set_data(self, data):
        """Sets entire data dictionary."""
        try:
            self.mutex.acquire()
            self.data = data
        finally:
            self.mutex.release()

    def clear_data(self):
        """Clears entire data dictionary."""
        try:
            self.mutex.acquire()
            self.data = {}
        finally:
            self.mutex.release()




More information about the Python-list mailing list