metaclasses, how you might actually use 'em

Michele Simionato mis6 at pitt.edu
Mon Apr 28 17:07:45 EDT 2003


Jack Diederich <jack at performancedrivers.com> wrote in message news:<mailman.1051549553.26987.python-list at python.org>...

> <snip> 
> I could never get the __new__ to do what I wanted.  I would always end up
> recursively calling __new__.  Doing everything in __init__ works, so I just
> kept with that.
> 
> -jackdied
> http://jackdied.com/code/

Yes, __init__ is less tricky than __new__. In order to avoid the
recursion you must do something like this:

class M(type):
    def __new__(meta,name,bases,dic):
        # do something
        return type.__new__(meta,name,bases,dic)

However, this is not cooperative. It is better to write

class M(type):
    def __new__(meta,name,bases,dic):
	# do something
	return super(M,meta).__new__(meta,name,bases,dic)

BTW, you should write your __init__ in this way:

class M(type):
    def __init__(cls,name,bases,dic):
	super(M,cls).__init__(name,bases,dic)
        # do something

This ensures safeness against multiple inheritance of metaclasses, which
soon or later you will be forced to use (to avoid metatype conflicts).


                      Michele




More information about the Python-list mailing list