interface.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. Cement core interface module.
  3. """
  4. from ..core import exc
  5. DEFAULT_META = ['interface', 'label', 'config_defaults', 'config_section']
  6. class Interface(object):
  7. """
  8. An interface definition class. All Interfaces should subclass from
  9. here. Note that this is not an implementation and should never be
  10. used directly.
  11. """
  12. def __init__(self):
  13. raise exc.InterfaceError("Interfaces can not be used directly.")
  14. class Attribute(object):
  15. """
  16. An interface attribute definition.
  17. :param description: The description of the attribute.
  18. """
  19. def __init__(self, description):
  20. self.description = description
  21. def __repr__(self):
  22. return "<interface.Attribute - '%s'>" % self.description
  23. def validate(interface, obj, members=[], meta=DEFAULT_META):
  24. """
  25. A wrapper to validate interfaces.
  26. :param interface: The interface class to validate against
  27. :param obj: The object to validate.
  28. :param members: The object members that must exist.
  29. :param meta: The meta object members that must exist.
  30. :raises: cement.core.exc.InterfaceError
  31. """
  32. invalid = []
  33. if hasattr(obj, '_meta') and interface != obj._meta.interface:
  34. raise exc.InterfaceError("%s does not implement %s." %
  35. (obj, interface))
  36. for member in members:
  37. if not hasattr(obj, member):
  38. invalid.append(member)
  39. if not hasattr(obj, '_meta'):
  40. invalid.append("_meta")
  41. else:
  42. for member in meta:
  43. if not hasattr(obj._meta, member):
  44. invalid.append("_meta.%s" % member)
  45. if invalid:
  46. raise exc.InterfaceError("Invalid or missing: %s in %s" %
  47. (invalid, obj))