advice.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2003 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Class advice.
  15. This module was adapted from 'protocols.advice', part of the Python
  16. Enterprise Application Kit (PEAK). Please notify the PEAK authors
  17. (pje@telecommunity.com and tsarna@sarna.org) if bugs are found or
  18. Zope-specific changes are required, so that the PEAK version of this module
  19. can be kept in sync.
  20. PEAK is a Python application framework that interoperates with (but does
  21. not require) Zope 3 and Twisted. It provides tools for manipulating UML
  22. models, object-relational persistence, aspect-oriented programming, and more.
  23. Visit the PEAK home page at http://peak.telecommunity.com for more information.
  24. """
  25. from types import FunctionType
  26. try:
  27. from types import ClassType
  28. except ImportError:
  29. __python3 = True
  30. else:
  31. __python3 = False
  32. import sys
  33. def getFrameInfo(frame):
  34. """Return (kind,module,locals,globals) for a frame
  35. 'kind' is one of "exec", "module", "class", "function call", or "unknown".
  36. """
  37. f_locals = frame.f_locals
  38. f_globals = frame.f_globals
  39. sameNamespace = f_locals is f_globals
  40. hasModule = '__module__' in f_locals
  41. hasName = '__name__' in f_globals
  42. sameName = hasModule and hasName
  43. sameName = sameName and f_globals['__name__']==f_locals['__module__']
  44. module = hasName and sys.modules.get(f_globals['__name__']) or None
  45. namespaceIsModule = module and module.__dict__ is f_globals
  46. if not namespaceIsModule:
  47. # some kind of funky exec
  48. kind = "exec"
  49. elif sameNamespace and not hasModule:
  50. kind = "module"
  51. elif sameName and not sameNamespace:
  52. kind = "class"
  53. elif not sameNamespace:
  54. kind = "function call"
  55. else: # pragma: no cover
  56. # How can you have f_locals is f_globals, and have '__module__' set?
  57. # This is probably module-level code, but with a '__module__' variable.
  58. kind = "unknown"
  59. return kind, module, f_locals, f_globals
  60. def addClassAdvisor(callback, depth=2):
  61. """Set up 'callback' to be passed the containing class upon creation
  62. This function is designed to be called by an "advising" function executed
  63. in a class suite. The "advising" function supplies a callback that it
  64. wishes to have executed when the containing class is created. The
  65. callback will be given one argument: the newly created containing class.
  66. The return value of the callback will be used in place of the class, so
  67. the callback should return the input if it does not wish to replace the
  68. class.
  69. The optional 'depth' argument to this function determines the number of
  70. frames between this function and the targeted class suite. 'depth'
  71. defaults to 2, since this skips this function's frame and one calling
  72. function frame. If you use this function from a function called directly
  73. in the class suite, the default will be correct, otherwise you will need
  74. to determine the correct depth yourself.
  75. This function works by installing a special class factory function in
  76. place of the '__metaclass__' of the containing class. Therefore, only
  77. callbacks *after* the last '__metaclass__' assignment in the containing
  78. class will be executed. Be sure that classes using "advising" functions
  79. declare any '__metaclass__' *first*, to ensure all callbacks are run."""
  80. # This entire approach is invalid under Py3K. Don't even try to fix
  81. # the coverage for this block there. :(
  82. if __python3: # pragma: no cover
  83. raise TypeError('Class advice impossible in Python3')
  84. frame = sys._getframe(depth)
  85. kind, module, caller_locals, caller_globals = getFrameInfo(frame)
  86. # This causes a problem when zope interfaces are used from doctest.
  87. # In these cases, kind == "exec".
  88. #
  89. #if kind != "class":
  90. # raise SyntaxError(
  91. # "Advice must be in the body of a class statement"
  92. # )
  93. previousMetaclass = caller_locals.get('__metaclass__')
  94. if __python3: # pragma: no cover
  95. defaultMetaclass = caller_globals.get('__metaclass__', type)
  96. else:
  97. defaultMetaclass = caller_globals.get('__metaclass__', ClassType)
  98. def advise(name, bases, cdict):
  99. if '__metaclass__' in cdict:
  100. del cdict['__metaclass__']
  101. if previousMetaclass is None:
  102. if bases:
  103. # find best metaclass or use global __metaclass__ if no bases
  104. meta = determineMetaclass(bases)
  105. else:
  106. meta = defaultMetaclass
  107. elif isClassAdvisor(previousMetaclass):
  108. # special case: we can't compute the "true" metaclass here,
  109. # so we need to invoke the previous metaclass and let it
  110. # figure it out for us (and apply its own advice in the process)
  111. meta = previousMetaclass
  112. else:
  113. meta = determineMetaclass(bases, previousMetaclass)
  114. newClass = meta(name,bases,cdict)
  115. # this lets the callback replace the class completely, if it wants to
  116. return callback(newClass)
  117. # introspection data only, not used by inner function
  118. advise.previousMetaclass = previousMetaclass
  119. advise.callback = callback
  120. # install the advisor
  121. caller_locals['__metaclass__'] = advise
  122. def isClassAdvisor(ob):
  123. """True if 'ob' is a class advisor function"""
  124. return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass')
  125. def determineMetaclass(bases, explicit_mc=None):
  126. """Determine metaclass from 1+ bases and optional explicit __metaclass__"""
  127. meta = [getattr(b,'__class__',type(b)) for b in bases]
  128. if explicit_mc is not None:
  129. # The explicit metaclass needs to be verified for compatibility
  130. # as well, and allowed to resolve the incompatible bases, if any
  131. meta.append(explicit_mc)
  132. if len(meta)==1:
  133. # easy case
  134. return meta[0]
  135. candidates = minimalBases(meta) # minimal set of metaclasses
  136. if not candidates: # pragma: no cover
  137. # they're all "classic" classes
  138. assert(not __python3) # This should not happen under Python 3
  139. return ClassType
  140. elif len(candidates)>1:
  141. # We could auto-combine, but for now we won't...
  142. raise TypeError("Incompatible metatypes",bases)
  143. # Just one, return it
  144. return candidates[0]
  145. def minimalBases(classes):
  146. """Reduce a list of base classes to its ordered minimum equivalent"""
  147. if not __python3: # pragma: no cover
  148. classes = [c for c in classes if c is not ClassType]
  149. candidates = []
  150. for m in classes:
  151. for n in classes:
  152. if issubclass(n,m) and m is not n:
  153. break
  154. else:
  155. # m has no subclasses in 'classes'
  156. if m in candidates:
  157. candidates.remove(m) # ensure that we're later in the list
  158. candidates.append(m)
  159. return candidates