[Tutor] Saving class data to a text file

Javier Ruere javier at ruere.com.ar
Sat Jul 16 21:03:28 CEST 2005

Darryl Luff wrote:
> [...] I created get/set methods for each field to avoid
> problems if I mis-type the dictionary keys.

 An automated way to do that:

class M(type):
    def create_properties(cls, obj, *prop_names, **prop_names_values):
        for pname in prop_names:
            setattr(cls, pname, cls._create_property(pname))

        for pname, value in prop_names_values.iteritems():
            setattr(cls, pname, cls._create_property(pname, value))

    def _create_property(cls, pname, init_value = None):
        container_name = '__' + pname

        def setter(self, value): setattr(self, container_name, value)
        def getter(self):
            if not hasattr(self, container_name):
                return init_value
            return getattr(self, container_name)

        return property(getter, setter)

class A(object):
    __metaclass__ = M

    def __init__(self):
        A.create_properties(self, 'prop1', 'prop2', prop3=8, **{'prop4':9})

a = A()
print a.prop1
a.prop1 = 3
print a.prop1
print a.prop3
a.prop3 = 'asdf'
print a.prop3
print a.prop4

> Now I have a couple of questions:
> - What is the recommended 'python' way to implement this class? and

  Don't know.

> - If what I'm doing is OK, is there an easy way to load a dictionary
> from the string representation without parsing the string manually?

  I wouldn't write the dictionary directly to a file, I would use ConfigParser.
  An easy but terribly insecure way to do what you ask is using eval (for ex.: eval(`{ 1:1 }`) ) but I do not recommend this.


PS: M was my first metaclass! :) If the same result can be achieved without one I would like to know the way.

More information about the Tutor mailing list