how to dynamically instantiate an object inheriting from severalclasses?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe Strout

    how to dynamically instantiate an object inheriting from severalclasses?

    I have a function that takes a reference to a class, and then
    instantiates that class (and then does several other things with the
    new instance). This is easy enough:

    item = cls(self, **itemArgs)

    where "cls" is the class reference, and itemArgs is obviously a set of
    keyword arguments for its __init__ method.

    But now I want to generalize this to handle a set of mix-in classes.
    Normally you use mixins by creating a class that derives from two or
    more other classes, and then instantiate that custom class. But in my
    situation, I don't know ahead of time which mixins might be used and
    in what combination. So I'd like to take a list of class references,
    and instantiate an object that derives from all of them, dynamically.

    Is this possible? If so, how?

    Thanks,
    - Joe

  • Arnaud Delobelle

    #2
    Re: how to dynamically instantiate an object inheriting from several classes?

    Joe Strout <joe@strout.net writes:
    I have a function that takes a reference to a class, and then
    instantiates that class (and then does several other things with the
    new instance). This is easy enough:
    >
    item = cls(self, **itemArgs)
    >
    where "cls" is the class reference, and itemArgs is obviously a set of
    keyword arguments for its __init__ method.
    >
    But now I want to generalize this to handle a set of mix-in classes.
    Normally you use mixins by creating a class that derives from two or
    more other classes, and then instantiate that custom class. But in my
    situation, I don't know ahead of time which mixins might be used and
    in what combination. So I'd like to take a list of class references,
    and instantiate an object that derives from all of them, dynamically.
    >
    Is this possible? If so, how?
    Of course it's possible: use type(name, bases, dict).
    >>class A(object): pass
    ....
    >>class B(object): pass
    ....
    >>C = type('C', (A, B), {})
    >>issubclass( C, A)
    True
    >>issubclass( C, B)
    True

    Call-by-object'ly yours

    --
    Arnaud

    Comment

    • George Sakkis

      #3
      Re: how to dynamically instantiate an object inheriting from severalclasses?

      On Nov 21, 5:11 pm, Joe Strout <j...@strout.ne twrote:
      I have a function that takes a reference to a class, and then  
      instantiates that class (and then does several other things with the  
      new instance).  This is easy enough:
      >
          item = cls(self, **itemArgs)
      >
      where "cls" is the class reference, and itemArgs is obviously a set of  
      keyword arguments for its __init__ method.
      >
      But now I want to generalize this to handle a set of mix-in classes.  
      Normally you use mixins by creating a class that derives from two or  
      more other classes, and then instantiate that custom class.  But in my  
      situation, I don't know ahead of time which mixins might be used and  
      in what combination.  So I'd like to take a list of class references,  
      and instantiate an object that derives from all of them, dynamically.
      >
      Is this possible?  If so, how?
      Easily:

      derived_cls = type('Derived', (cls1, cls2, *rest_classes), {})
      item = derived_cls(**i temArgs)

      You will probably want to cache the generated classes so that at most
      one class is created for each combination of mixins.

      HTH,
      George

      Comment

      • Joe Strout

        #4
        Re: how to dynamically instantiate an object inheriting from severalclasses?

        On Nov 21, 2008, at 3:30 PM, Arnaud Delobelle wrote:
        Of course it's possible: use type(name, bases, dict).
        Thanks, I never knew about that form of type(). Neither does the
        2.5.2 reference manual, whose only index entry for the type() function
        is <http://www.python.org/doc/2.5.2/ref/objects.html#l2 h-21>, and that
        speaks only about the traditional use of type() to check the type of
        an object.

        help(type) does mention the form you show, though it doesn't explain
        what the dict is for.

        Where would I find documentation on this nifty function?

        Thanks,
        - Joe


        Comment

        • Ned Deily

          #5
          Re: how to dynamically instantiate an object inheriting from severalclasses?

          In article <0E0333C1-9515-4736-A839-F59AAD675D4E@st rout.net>,
          Joe Strout <joe@strout.net wrote:
          On Nov 21, 2008, at 3:30 PM, Arnaud Delobelle wrote:
          Of course it's possible: use type(name, bases, dict).
          Thanks, I never knew about that form of type(). Neither does the
          2.5.2 reference manual, whose only index entry for the type() function
          is <http://www.python.org/doc/2.5.2/ref/objects.html#l2 h-21>, and that
          speaks only about the traditional use of type() to check the type of
          an object.
          >
          help(type) does mention the form you show, though it doesn't explain
          what the dict is for.
          >
          Where would I find documentation on this nifty function?
          Where built-in functions are documented, the Python Library Reference:

          <http://www.python.org/doc/2.5.2/lib/built-in-funcs.html>

          --
          Ned Deily,
          nad@acm.org

          Comment

          • Joe Strout

            #6
            Re: how to dynamically instantiate an object inheriting from severalclasses?

            On Nov 21, 2008, at 6:06 PM, Ned Deily wrote:
            >Where would I find documentation on this nifty function?
            >
            Where built-in functions are documented, the Python Library Reference:
            >
            <http://www.python.org/doc/2.5.2/lib/built-in-funcs.html>
            Perfect, thank you. (Odd that the index entry for type() doesn't link
            to this page.)

            Best,
            - Joe


            Comment

            • Steve Holden

              #7
              Re: how to dynamically instantiate an object inheriting from severalclasses?

              Joe Strout wrote:
              On Nov 21, 2008, at 6:06 PM, Ned Deily wrote:
              >
              >>Where would I find documentation on this nifty function?
              >>
              >Where built-in functions are documented, the Python Library Reference:
              >>
              ><http://www.python.org/doc/2.5.2/lib/built-in-funcs.html>
              >
              Perfect, thank you. (Odd that the index entry for type() doesn't link
              to this page.)
              Yeah, the indexing isn't perfect. Not sure what to do about that without
              filing bugs for each case (which I am as guilty of not doing as anyone
              else).

              regards
              Steve
              --
              Steve Holden +1 571 484 6266 +1 800 494 3119
              Holden Web LLC http://www.holdenweb.com/

              Comment

              • Steven D'Aprano

                #8
                Re: how to dynamically instantiate an object inheriting fromseveralclas ses?

                On Fri, 21 Nov 2008 15:11:20 -0700, Joe Strout wrote:
                I have a function that takes a reference to a class,
                Hmmm... how do you do that from Python code? The simplest way I can think
                of is to extract the name of the class, and then pass the name as a
                reference to the class, and hope it hasn't been renamed in the meantime:

                def foo(cls_name, item_args):
                # Won't necessarily work for nested scopes.
                cls = globals()[cls_name]
                item = cls(**itemArgs)
                return item

                instance = foo(Myclass.__n ame__, {'a':1})

                Seems awfully complicated. If I were you, I'd forget the extra layer of
                indirection and just pass the class itself, rather than trying to
                generate some sort of reference to it. Let the Python virtual machine
                worry about what is the most efficient mechanism to use behind the scenes.


                [...]
                But now I want to generalize this to handle a set of mix-in classes.
                Normally you use mixins by creating a class that derives from two or
                more other classes, and then instantiate that custom class. But in my
                situation, I don't know ahead of time which mixins might be used and in
                what combination. So I'd like to take a list of class references, and
                instantiate an object that derives from all of them, dynamically.
                >
                Is this possible? If so, how?
                It sounds like you need to generate a new class on the fly. Here's one
                way:

                # untested
                def foo(cls, item_args, mixins=None):
                superclasses = [cls] + (mixins or [])
                class MixedClass(*sup erclasses):
                pass
                item = MixedClass(**it emArgs)
                return item

                instance = foo(MyClass, {'a':1}, [Aclass, Bclass, Cclass])


                --
                Steven

                Comment

                Working...