I am looking for a way in python to build classes in python that:
- setter check the type of the value before assignment
- impossible to add new class attribute
for the time being I found those two decorators:
def getter_setter_gen(name, type_): def getter(self): return getattr(self, "__" + name) def setter(self, value): print "setter", value if not isinstance(value, type_): raise TypeError("%s attribute must be set to an instance of %s" % (name, type_)) setattr(self, "__" + name, value) return property(getter, setter) def auto_attr_check(cls): new_dct = {} print "auto_attr_check", cls.__dict__.items() for key, value in cls.__dict__.items(): if isinstance(value, type): value = getter_setter_gen(key, value) new_dct[key] = value # Creates a new class, using the modified dictionary as the class dict: n = type(cls)(cls.__name__, cls.__bases__, new_dct) return n
and
def froze_it(cls): def frozensetattr(self, key, value): print key key = ''+key print(dir(self)) print key if not hasattr(self, key): raise TypeError("Class {} is frozen. Cannot set {} = {}" .format(cls.__name__, key, value)) else: object.__setattr__(self, key, value) cls.__setattr__ = frozensetattr return cls
but I have a lot of trouble to join those two approach. Can you help me? Do you have ideas? Thanks a lot