interface.py 1.9 KB

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