Making classes from Metaclasses globally available

David MacQuigg dmq at gain.com
Wed Jun 16 21:29:56 CEST 2004


On Wed, 16 Jun 2004 00:28:46 -0400, "Jean-François Doyon"
<jfdoyon at methane.ca> wrote:

>Hello,
>
>I'm using MetaClasses to create classes.

Why use metaclasses?  The metaclass wizards seem to be telling us that
these are special tools for Python developers, not intended for
"mortal users".

>How do I make these new classes "globally" available?

Can't you just generate your classes with an ordinary function, and
assign them to whatever global name you want?

def factory(var1,func1):
    class C:
        const1 = 123
        def commonfunc(self):
            print "Hello from commonfunc"
    setattr(C, 'var1', var1)
    setattr(C, func1.__name__, func1)
    return C

Then whenever you need a new class, just call the factory with
whatever variable data and functions you want to add to each class.

C1 = factory(var1,func1)  # A unique class
c1 = C1()                 # An instance of that class

-- Dave

*************************************************************     *
* David MacQuigg, PhD              * email:  dmq at gain.com      *  *
* IC Design Engineer               * phone:  USA 520-721-4583  *  *  *
* Analog Design Methodologies                                  *  *  *
*                                  * 9320 East Mikelyn Lane     * * *
* VRS Consulting, P.C.             * Tucson, Arizona 85710        *
*************************************************************     *


>I probably just have to assign them to something magic, but I can't seem to
>figure out which one.
>
>if I do:
>
>MetaClass('Klass', (), {})
>
>The resulting class needs to be assigned to something:
>
>    myclass = MetaClass('Klass', (), {})
>
>The problem is that I'm  looping and don't know in advance how many classes
>there will be.
>
>So right now I have something like:
>
>msclasses[clsname] = MapServerMetaClass(str(clsname), (),
>{'schema':list,'__init__':MapServerClassInit})
>
>inside a loop.
>
>Problem is I really don't want to have the classes stuck inside that dict.
>I want them "globally" available as if I had simply made a "class"
>declaration at the top of the file.
>
>Any ideas or suggestions?
>
>Thanks,
>J.F.
>




More information about the Python-list mailing list