[CentralOH] Data Members / Properties - 2 questions

Neil Ludban nludban at osc.edu
Sun Feb 14 15:53:27 CET 2010


On Feb 13, 2010, at 9:54 PM, Mark Erbaugh wrote:
> The problem I have is that in some places, the existing code accesses these data members indirectly passing a string version of the data name (i.e. 'SHOW_QTY').  With a data member, it's a simple matter to look up the data in the container's __dict__.

That was a Bad Idea from the beginning, the original programmer should
have written their own utility methods even if they didn't know about
the builtin getattr and setattr functions.  The only reason to access
__dict__ is to bypass all the regular mechanisms.


> There are several more properties like this. Is there a way to iterate through a sequence (i.e. (SHOW_QTY, BY_PILL, ...)) and have the getters, setters and properties created automatically?

I wouldn't suggest this for new code, but as a quick and dirty hack
to fix existing code it seems ok.  The idea is to override __getattr__
and __setattr__ so you don't have to manually create all the properties,
and do it in a dummy object so you don't have to change the original
to set internal state using __dict__.  Then rename the original class
and replace it with a function so none of the client code has to know
about the change.  Depending on your application, it might be safer
to replace the hasattr(...) test with a regular expression or verify
the name is in a known set.

class AttrWrapper(object):

    def __init__(self, obj):
        self.__obj = obj

    def __getattr__(self, name):
        if hasattr(self.__obj, name):
            return getattr(self.__obj, name)
        else:
            return self.__obj._getAUDIT(name)

    def __setattr__(self, name, value):
        if hasattr(self.__obj, name):
            setattr(self.__obj, name, value)
        else:
            self.__obj._setAUDIT(name, value)

class _DataContainer(object): pass

def DataContainer(*args, **kwargs):
    return AttrWrapper(_DataContainer(*args, **kwargs))



More information about the CentralOH mailing list