cooperation of buitlin methods usingtsuper

Matthias Oberlaender matthias.oberlaender at REMOVE.daimlerchrysler.com
Wed Jul 2 13:53:10 CEST 2003


I would like  to adopt the cooperation paradigm in conjunction with builtin 
methods and operators, such as len, iter, +, * etc. 

But the direct approach does not work with the current implementation of 
super. For example, 'len(super(Y, y)' will always result in 'len() of unsized 
object'.

As far as I understand, this is because builtins don't use a dynamic lookup 
chain, but go directly to the slots for the builtins. However, super returns 
an instance of class 'super'. Since all super objects share this class,  its 
slots will not be filled as one might hope. 

My workaround is this: I create a subclass of 'super' on the fly each time I 
call 'mysuper'.  Look at the definition below.  It seems to work. But maybe I 
have overlooked something. Is my understanding correct? Is 'mysuper' a good 
solution? Possible improvements? (e.g. caching of subclasses)

Thanks for comments!


import new
 
class X(object):
  def __len__(self): return 2222

class Y(X):
  def __len__(self): return 1111

def mysuper(cls, inst):
  return new.classobj('mysuper', (super,) + cls.__bases__, {})(cls, inst)

y = Y()
try:
  print len(super(Y, y))
except Exception, msg:
  print msg

try:
  print len(mysuper(Y, y))
except Exception, msg:
  print msg

Output:

len() of unsized object
2222

-- 
 ____  __  _/_/ . 
( / / ( /  / / /  

=====================================================================
Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm
RIC/AP (Machine Perception)
Wilhelm-Runge-Str. 11,  P.O. Box 2360,  89013 Ulm, Germany
Phone: +49 731 505 2354       Fax: +49 731 505 4105
Email: matthias.oberlaender at VOID.daimlerchrysler.com
=====================================================================





More information about the Python-list mailing list