why * is not like unquote (scheme)

Carl Banks imbosol-1048171824 at aerojockey.com
Thu Mar 20 10:07:45 EST 2003


Alex Martelli wrote:
> Peter Hansen wrote:
> 
>> Amir Hadar wrote:
>>> 
>>> I'me tring to create a factory function that create a class as follow:
>>> 
>>> def CreatePreviewFrame(*addins):
>>>     class tmp(cPreviewFrame,*addins):
>>>         pass
>>>     return tmp
>   ,,,
>> Maybe this is a rare case where you'll need to use exec to
>> get the job done right.
> 
> No!  Module new is what you need:
> 
> import new
> def CreatePreviewFrame(*addins):
>    return new.classobj( 'tmp', (cPreviewFrame)+addins, {} )


Except the OP may have been using "pass" just to simplify things.  His
real class might have some stuff in it, which makes using this as-is
kind of unwieldy.

Of course, that's what metaclasses are for.

    class type_with_programmable_bases(type):
        def __new__(cls,name,bases,classdict):
            bases += classdict.get('__bases__',())
	    return type.__new__(cls,name,bases,classdict)


Then, in cPreviewFrame, set the metaclass:

    class cPreviewFrame(whatever):
        ...
        __metaclass__ = type_with_programmable_bases


Then, the factory function becomes:

    def CreatePreviewFrame(*addins):
        class tmp(cPreviewFrame):
            __bases__ = addins
	    def any_other_function(self):
	        pass
            def some_other_function(self):
                pass
        return tmp


-- 
CARL BANKS




More information about the Python-list mailing list