How can I dynamically insert a base class in a given class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 10 20:44:59 EDT 2009


En Sun, 10 May 2009 00:04:17 -0300, Дамјан Георгиевски <gdamjan at gmail.com>  
escribió:

> How can I dynamically insert a base class in a given class? Yeah, I'm
> writing a class decorator that needs to manipulate the class by
> inserting another base class in it.

In this case, as you want to modify the base classes, I think a metaclass  
is more apropiate (the decorator acts too late, *after* the class has  
already been created).
Based on your code:

class ReallyBase(object):
    def someimportantmethod(self):
      return 'really really'

def dynamically_determine_metaclass(args):

     class MyMetaclass(type):
        def __new__(meta, name, bases, namespace):
          bases = (ReallyBase,) + bases
          namespace['some_value'] = args
          return type.__new__(meta, name, bases, namespace)

     return MyMetaclass

class Unsuspecting(object):
    __metaclass__ = dynamically_determine_metaclass(123)
    def stuff(self):
      return "ok"

u = Unsuspecting()
print u.stuff(), u.someimportantmethod(), u.some_value,  
Unsuspecting.some_value

-- 
Gabriel Genellina




More information about the Python-list mailing list