Create class definitions of properties (typed and ordered) with metaclass


/ Published in: Python
Save to your folder(s)

Like Django.models, GAE.db.model or SqlAlchemy definitions


Copy this code and paste it in your HTML
  1. import os
  2.  
  3. class _FieldBase_:
  4. _defines=[]
  5. def __init__(self,*a):
  6. _FieldBase_._defines.append(self)
  7.  
  8. class _FieldedMetaClass_(type):
  9. def __init__(cls, name, bases, dct):
  10. super(_FieldedMetaClass_, cls).__init__(name, bases, dct)
  11. if name!="Form":
  12. fields_to_name = dict([(slot,name) for name,slot in dct.items() if isinstance(slot,_FieldBase_)])
  13. cls.fields = [(fields_to_name[obj],obj ) for obj in _FieldBase_._defines]
  14. _FieldBase_._defines=[] # reset list !!!
  15.  
  16. class Form (object):
  17. __metaclass__ = _FieldedMetaClass_
  18.  
  19. def __repr__(self):
  20. l=["Form '%s'"%self.__class__.__name__]
  21. l+=["* %-10s : %s"%(f,t.__class__.__name__) for f,t in self.fields]
  22. return os.linesep.join(l)
  23.  
  24. class FieldInt(_FieldBase_):
  25. def __init__(self,*a):
  26. _FieldBase_.__init__(self,a)
  27.  
  28. class FieldString(_FieldBase_):
  29. def __init__(self,*a):
  30. _FieldBase_.__init__(self,a)
  31.  
  32. class Form1(Form):
  33. name = FieldString(1)
  34. surname = FieldString(2)
  35. age = FieldInt(3)
  36.  
  37. class Form2(Form):
  38. nb = FieldInt(1)
  39. title = FieldString(2)
  40.  
  41. print Form1()
  42. print Form2()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.