newsuper.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. '''
  2. This module provides a newsuper() function in Python 2 that mimics the
  3. behaviour of super() in Python 3. It is designed to be used as follows:
  4. from __future__ import division, absolute_import, print_function
  5. from future.builtins import super
  6. And then, for example:
  7. class VerboseList(list):
  8. def append(self, item):
  9. print('Adding an item')
  10. super().append(item) # new simpler super() function
  11. Importing this module on Python 3 has no effect.
  12. This is based on (i.e. almost identical to) Ryan Kelly's magicsuper
  13. module here:
  14. https://github.com/rfk/magicsuper.git
  15. Excerpts from Ryan's docstring:
  16. "Of course, you can still explicitly pass in the arguments if you want
  17. to do something strange. Sometimes you really do want that, e.g. to
  18. skip over some classes in the method resolution order.
  19. "How does it work? By inspecting the calling frame to determine the
  20. function object being executed and the object on which it's being
  21. called, and then walking the object's __mro__ chain to find out where
  22. that function was defined. Yuck, but it seems to work..."
  23. '''
  24. from __future__ import absolute_import
  25. import sys
  26. from types import FunctionType
  27. from future.utils import PY3, PY26
  28. _builtin_super = super
  29. _SENTINEL = object()
  30. def newsuper(typ=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
  31. '''Like builtin super(), but capable of magic.
  32. This acts just like the builtin super() function, but if called
  33. without any arguments it attempts to infer them at runtime.
  34. '''
  35. # Infer the correct call if used without arguments.
  36. if typ is _SENTINEL:
  37. # We'll need to do some frame hacking.
  38. f = sys._getframe(framedepth)
  39. try:
  40. # Get the function's first positional argument.
  41. type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
  42. except (IndexError, KeyError,):
  43. raise RuntimeError('super() used in a function with no args')
  44. try:
  45. # Get the MRO so we can crawl it.
  46. mro = type_or_obj.__mro__
  47. except (AttributeError, RuntimeError): # see issue #160
  48. try:
  49. mro = type_or_obj.__class__.__mro__
  50. except AttributeError:
  51. raise RuntimeError('super() used with a non-newstyle class')
  52. # A ``for...else`` block? Yes! It's odd, but useful.
  53. # If unfamiliar with for...else, see:
  54. #
  55. # http://psung.blogspot.com/2007/12/for-else-in-python.html
  56. for typ in mro:
  57. # Find the class that owns the currently-executing method.
  58. for meth in typ.__dict__.values():
  59. # Drill down through any wrappers to the underlying func.
  60. # This handles e.g. classmethod() and staticmethod().
  61. try:
  62. while not isinstance(meth,FunctionType):
  63. if isinstance(meth, property):
  64. # Calling __get__ on the property will invoke
  65. # user code which might throw exceptions or have
  66. # side effects
  67. meth = meth.fget
  68. else:
  69. try:
  70. meth = meth.__func__
  71. except AttributeError:
  72. meth = meth.__get__(type_or_obj, typ)
  73. except (AttributeError, TypeError):
  74. continue
  75. if meth.func_code is f.f_code:
  76. break # Aha! Found you.
  77. else:
  78. continue # Not found! Move onto the next class in MRO.
  79. break # Found! Break out of the search loop.
  80. else:
  81. raise RuntimeError('super() called outside a method')
  82. # Dispatch to builtin super().
  83. if type_or_obj is not _SENTINEL:
  84. return _builtin_super(typ, type_or_obj)
  85. return _builtin_super(typ)
  86. def superm(*args, **kwds):
  87. f = sys._getframe(1)
  88. nm = f.f_code.co_name
  89. return getattr(newsuper(framedepth=2),nm)(*args, **kwds)
  90. __all__ = ['newsuper']