views:

87

answers:

1

Hello,

What I have below is a class I made to easily store a bunch of data as attributes. They wind up getting stored in a dictionary. I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units. When I started overriding __setattr__ I was having trouble creating that initial dicionary in the 2nd line of __init__ like so...

super(MyDataFile, self).__setattr__('_data', {})

My question... Is there an easier way to create a class level attribute with going through __setattr__? Also, should I be concerned about keeping a separate dictionary or should I just store everything in self.__dict__?

#!/usr/bin/env python

from unitconverter import convert
import re

special_attribute_re = re.compile(r'(.+)__(.+)')

class MyDataFile(object):

    def __init__(self, *args, **kwargs):
        super(MyDataFile, self).__init__(*args, **kwargs)
        super(MyDataFile, self).__setattr__('_data', {})

    #
    # For attribute type access
    #
    def __setattr__(self, name, value):
        self._data[name] = value

    def __getattr__(self, name):

        if name in self._data:
            return self._data[name]

        match = special_attribute_re.match(name)
        if match:
            varname, units = match.groups()
            if varname in self._data:
                return self.getvaras(varname, units)

        raise AttributeError

    #
    # other methods
    #
    def getvaras(self, name, units):
        from_val, from_units = self._data[name]
        if from_units == units:
            return from_val
        return convert(from_val, from_units, units), units

    def __str__(self):
        return str(self._data)



d = MyDataFile()

print d

# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'

# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC

# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm
A: 

Your __setattr__ in the example doesn't do anything except put things in _data instead of __dict__ Remove it.

Change your __getattr__ to use __dict__.

Store your value and units as a simple 2-tuple.

S.Lott