Using metaclasses to make super more beatiful

Michele Simionato mis6 at pitt.edu
Thu Jun 5 23:38:10 CEST 2003


Gerrit Holl <gerrit at nl.linux.org> wrote in message news:<mailman.1054831871.3625.python-list at python.org>...
> Hi,
> 
> as demonstrated by Guido's paper[0], a relatively simple metaclass
> can make the use of super a lot more beatiful:
> 
>  97 >>> class autosuper(type):
>  97 ...  def __init__(cls, name, bases, dict):
>  97 ...   super(autosuper, cls).__init__(name, bases, dict)
>  97 ...   setattr(cls, "super", super(cls))
>  97 ...
>  98 >>> class A:
>  98 ...  __metaclass__ = autosuper
>  98 ...  def f(self): return "A"
>  98 ...
> 100 >>> class B(A):
> 100 ...  def f(self):
> 100 ...   return self.super.f()
> 100 ...
> 101 >>> B()
> <__main__.B object at 0x403b3c6c>
> 102 >>> B().f()
> 'A'
> 
> Why doesn't type include the behaviour of autosuper by default,
> so that each class can use self.super or self.__super__ so that
> using super is easier?

Notice that Guido has been clever than you and he has used a private 
attribute .__super,  not just .super. Doing your way is not safe under
inheritance, as Just pointed out. Here is an exercise for you: try to 
understand the difference between the following two programs:

 # program 1

  class B(object):
       def __init__(self): 
          print self.__this,'.__init__'
  B._B__this=B

  class C(B):
      def __init__(self):
         super(self.__this,self).__init__() # cooperative __init__ 
         print self.__this,'.__init__'
  C._C__this=C

  C()

  # output:
  # <class '__main__.B'> .__init__
  # <class '__main__.C'> .__init__


and

  # program 2


class B(object):
    def __init__(self): 
        print self.this,'.__init__'
B.this=B

class C(B):
    def __init__(self):
        super(self.this,self).__init__() # cooperative __init__ 
        print self.this,'.__init__'
C.this=C

C()

  # output:
  # <class '__main__.C'> .__init__
  # <class '__main__.C'> .__init__

> And, is it convention not to use Capitalization for metaclasses?
> In three examples, Guido doensn't do it in his paper[0]!
> 
> [0] http://www.python.org/2.2.3/descrintro.html#metaclasses
> 
> yours,
> Gerrit.

I always use capitalization for metaclasses, they are classes, not
functions! I think you are free to do as you wish, anyway. My suggestion
(actually it is not mine, it comes from the metaclass book) is to use
adjective as metaclass names (notice that Guido does not do that).

Have fun,

                                     Michele


P.S. shameless, I point you to

http://www-106.ibm.com/developerworks/library/l-pymeta.html

and I anticipate that we will write a second paper on the
subject very soon !




More information about the Python-list mailing list