[Python-3000] auto-super()

Josiah Carlson jcarlson at uci.edu
Wed Apr 19 02:15:02 CEST 2006


"Guido van Rossum" <guido at python.org> wrote:
> Let's leave this topic behind for a while. Hacks that can be
> implemented only using sys._getframe() are not generally suitable for
> including in the standard library or making part of the language spec.

Assuming name uniqueness among all classes in the mro, assuming the mro
is available in other implementations, assuming name mangling for
__attributes are consistant, and assuming that one checks for attributes
on supers before calling, one can do it without frame hacking [1],
though I don't know how it compares (in terms of speed) to super(cls,
self) .


 - Josiah

[1]
>>> class Super(object):
...     def __getattr__(self, key):
...         if key.endswith('__superclass'):
...             name = key[1:-12]
...             for cls in self.__class__.__mro__:
...                 if cls.__name__ == name:
...                     return cls
...         raise AttributeError, "%s instance has no attribute %s"%(
...             self.__class__.__name__, key)
...
>>> class foo(Super):
...     def go(self):
...         print "in foo"
...         super(self.__superclass, self).go()
...
>>> class bar(foo):
...     def go(self):
...         print "in bar"
...         super(self.__superclass, self).go()
...
>>> bar().go()
in bar
in foo
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in go
  File "<stdin>", line 4, in go
AttributeError: 'super' object has no attribute 'go'>>> class Super(object):
...     def __getattr__(self, key):
...         if key.endswith('__superclass'):
...             name = key[1:-12]
...             for cls in self.__class__.__mro__:
...                 if cls.__name__ == name:
...                     return cls
...         raise AttributeError, "%s instance has no attribute %s"%(
...             self.__class__.__name__, key)
...
>>> class foo(Super):
...     def go(self):
...         print "in foo"
...         super(self.__superclass, self).go()
...
>>> class bar(foo):
...     def go(self):
...         print "in bar"
...         super(self.__superclass, self).go()
...
>>> bar().go()
in bar
in foo
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in go
  File "<stdin>", line 4, in go
AttributeError: 'super' object has no attribute 'go'
>>> 



More information about the Python-3000 mailing list