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

  • Thread starter Дамјан ГеоргиевÑки
  • Start date
Ð

Дамјан ГеоргиевÑки

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.


Something like:

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

@expose(args)
class Unsuspecting(object):
def stuff(self):
return "ok"

I've come up with this ... but I'm sure it has some shortcomings

def expose(args):
def wrap(cls):
# do stuff with args and cls
return type(cls.__name__, cls.__bases__ + (ReallyBase,),
dict(cls.__dict__))
return wrap



--
дамјан ( http://softver.org.mk/damjan/ )

war is peace
freedom is slavery
restrictions are enablement
 
G

Gabriel Genellina

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top