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

Discussion in 'Python' started by Дамјан ГеоргиевÑки, May 10, 2009.

  1. 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
     
    Дамјан ГеоргиевÑки, May 10, 2009
    #1
    1. Advertising

  2. En Sun, 10 May 2009 00:04:17 -0300, Дамјан ГеоргиевÑки <>
    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
     
    Gabriel Genellina, May 11, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Lord0
    Replies:
    1
    Views:
    581
    Thomas Weidenfeller
    Apr 19, 2006
  2. chiara
    Replies:
    6
    Views:
    491
    Barry Schwarz
    Oct 6, 2005
  3. 2Barter.net
    Replies:
    0
    Views:
    380
    2Barter.net
    Dec 13, 2006
  4. Replies:
    7
    Views:
    460
    Adam Nielsen
    Sep 28, 2007
  5. Casey Hawthorne
    Replies:
    385
    Views:
    5,874
    ng2010
    Apr 4, 2010
Loading...

Share This Page