newsuper.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. typ = find_owner(type_or_obj, f.f_code)
  46. except (AttributeError, RuntimeError, TypeError):
  47. # see issues #160, #267
  48. try:
  49. typ = find_owner(type_or_obj.__class__, f.f_code)
  50. except AttributeError:
  51. raise RuntimeError('super() used with an old-style class')
  52. except TypeError:
  53. raise RuntimeError('super() called outside a method')
  54. # Dispatch to builtin super().
  55. if type_or_obj is not _SENTINEL:
  56. return _builtin_super(typ, type_or_obj)
  57. return _builtin_super(typ)
  58. def find_owner(cls, code):
  59. '''Find the class that owns the currently-executing method.
  60. '''
  61. for typ in cls.__mro__:
  62. for meth in typ.__dict__.values():
  63. # Drill down through any wrappers to the underlying func.
  64. # This handles e.g. classmethod() and staticmethod().
  65. try:
  66. while not isinstance(meth,FunctionType):
  67. if isinstance(meth, property):
  68. # Calling __get__ on the property will invoke
  69. # user code which might throw exceptions or have
  70. # side effects
  71. meth = meth.fget
  72. else:
  73. try:
  74. meth = meth.__func__
  75. except AttributeError:
  76. meth = meth.__get__(cls, typ)
  77. except (AttributeError, TypeError):
  78. continue
  79. if meth.func_code is code:
  80. return typ # Aha! Found you.
  81. # Not found! Move onto the next class in MRO.
  82. raise TypeError
  83. def superm(*args, **kwds):
  84. f = sys._getframe(1)
  85. nm = f.f_code.co_name
  86. return getattr(newsuper(framedepth=2),nm)(*args, **kwds)
  87. __all__ = ['newsuper']