advice.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. __all__ = [
  33. 'addClassAdvisor',
  34. 'determineMetaclass',
  35. 'getFrameInfo',
  36. 'isClassAdvisor',
  37. 'minimalBases',
  38. ]
  39. import sys
  40. def getFrameInfo(frame):
  41. """Return (kind,module,locals,globals) for a frame
  42. 'kind' is one of "exec", "module", "class", "function call", or "unknown".
  43. """
  44. f_locals = frame.f_locals
  45. f_globals = frame.f_globals
  46. sameNamespace = f_locals is f_globals
  47. hasModule = '__module__' in f_locals
  48. hasName = '__name__' in f_globals
  49. sameName = hasModule and hasName
  50. sameName = sameName and f_globals['__name__']==f_locals['__module__']
  51. module = hasName and sys.modules.get(f_globals['__name__']) or None
  52. namespaceIsModule = module and module.__dict__ is f_globals
  53. if not namespaceIsModule:
  54. # some kind of funky exec
  55. kind = "exec"
  56. elif sameNamespace and not hasModule:
  57. kind = "module"
  58. elif sameName and not sameNamespace:
  59. kind = "class"
  60. elif not sameNamespace:
  61. kind = "function call"
  62. else: # pragma: no cover
  63. # How can you have f_locals is f_globals, and have '__module__' set?
  64. # This is probably module-level code, but with a '__module__' variable.
  65. kind = "unknown"
  66. return kind, module, f_locals, f_globals
  67. def addClassAdvisor(callback, depth=2):
  68. """Set up 'callback' to be passed the containing class upon creation
  69. This function is designed to be called by an "advising" function executed
  70. in a class suite. The "advising" function supplies a callback that it
  71. wishes to have executed when the containing class is created. The
  72. callback will be given one argument: the newly created containing class.
  73. The return value of the callback will be used in place of the class, so
  74. the callback should return the input if it does not wish to replace the
  75. class.
  76. The optional 'depth' argument to this function determines the number of
  77. frames between this function and the targeted class suite. 'depth'
  78. defaults to 2, since this skips this function's frame and one calling
  79. function frame. If you use this function from a function called directly
  80. in the class suite, the default will be correct, otherwise you will need
  81. to determine the correct depth yourself.
  82. This function works by installing a special class factory function in
  83. place of the '__metaclass__' of the containing class. Therefore, only
  84. callbacks *after* the last '__metaclass__' assignment in the containing
  85. class will be executed. Be sure that classes using "advising" functions
  86. declare any '__metaclass__' *first*, to ensure all callbacks are run."""
  87. # This entire approach is invalid under Py3K. Don't even try to fix
  88. # the coverage for this block there. :(
  89. if __python3: # pragma: no cover
  90. raise TypeError('Class advice impossible in Python3')
  91. frame = sys._getframe(depth)
  92. kind, module, caller_locals, caller_globals = getFrameInfo(frame)
  93. # This causes a problem when zope interfaces are used from doctest.
  94. # In these cases, kind == "exec".
  95. #
  96. #if kind != "class":
  97. # raise SyntaxError(
  98. # "Advice must be in the body of a class statement"
  99. # )
  100. previousMetaclass = caller_locals.get('__metaclass__')
  101. if __python3: # pragma: no cover
  102. defaultMetaclass = caller_globals.get('__metaclass__', type)
  103. else:
  104. defaultMetaclass = caller_globals.get('__metaclass__', ClassType)
  105. def advise(name, bases, cdict):
  106. if '__metaclass__' in cdict:
  107. del cdict['__metaclass__']
  108. if previousMetaclass is None:
  109. if bases:
  110. # find best metaclass or use global __metaclass__ if no bases
  111. meta = determineMetaclass(bases)
  112. else:
  113. meta = defaultMetaclass
  114. elif isClassAdvisor(previousMetaclass):
  115. # special case: we can't compute the "true" metaclass here,
  116. # so we need to invoke the previous metaclass and let it
  117. # figure it out for us (and apply its own advice in the process)
  118. meta = previousMetaclass
  119. else:
  120. meta = determineMetaclass(bases, previousMetaclass)
  121. newClass = meta(name,bases,cdict)
  122. # this lets the callback replace the class completely, if it wants to
  123. return callback(newClass)
  124. # introspection data only, not used by inner function
  125. advise.previousMetaclass = previousMetaclass
  126. advise.callback = callback
  127. # install the advisor
  128. caller_locals['__metaclass__'] = advise
  129. def isClassAdvisor(ob):
  130. """True if 'ob' is a class advisor function"""
  131. return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass')
  132. def determineMetaclass(bases, explicit_mc=None):
  133. """Determine metaclass from 1+ bases and optional explicit __metaclass__"""
  134. meta = [getattr(b,'__class__',type(b)) for b in bases]
  135. if explicit_mc is not None:
  136. # The explicit metaclass needs to be verified for compatibility
  137. # as well, and allowed to resolve the incompatible bases, if any
  138. meta.append(explicit_mc)
  139. if len(meta)==1:
  140. # easy case
  141. return meta[0]
  142. candidates = minimalBases(meta) # minimal set of metaclasses
  143. if not candidates: # pragma: no cover
  144. # they're all "classic" classes
  145. assert(not __python3) # This should not happen under Python 3
  146. return ClassType
  147. elif len(candidates)>1:
  148. # We could auto-combine, but for now we won't...
  149. raise TypeError("Incompatible metatypes",bases)
  150. # Just one, return it
  151. return candidates[0]
  152. def minimalBases(classes):
  153. """Reduce a list of base classes to its ordered minimum equivalent"""
  154. if not __python3: # pragma: no cover
  155. classes = [c for c in classes if c is not ClassType]
  156. candidates = []
  157. for m in classes:
  158. for n in classes:
  159. if issubclass(n,m) and m is not n:
  160. break
  161. else:
  162. # m has no subclasses in 'classes'
  163. if m in candidates:
  164. candidates.remove(m) # ensure that we're later in the list
  165. candidates.append(m)
  166. return candidates