why * is not like unquote (scheme)

Alex Martelli aleax at aleax.it
Thu Mar 20 15:46:07 CET 2003

Peter Hansen wrote:
>> import new
>> def CreatePreviewFrame(*addins):
>>     return new.classobj( 'tmp', (cPreviewFrame)+addins, {} )
> Ah, thank you.  I've used only "module" from that module, based on
> some recipe, so I've never actually looked in it in...
> Time to take a tour, methinks. :-)

Except that in Python 2.3 you don't really need it any more, so
it may not be all that interesting any more... in general, types
are callable, and usually return new instances of themselves
when called with the right arguments.  A class's type is also
known as its metaclass, incidentally, and Python calls it (to
execute the class statement) with the same arguments I passed
to new.classobj above -- name string, tuple of bases, dict of
stuff specifically defined in the new class's body ({}, the
empty dict, is here equivalent to an empty classbody).

So, without any need for module new, you could do:

return type(cPreviewFrame)( 'tmp', (cPreviewFrame,)+addins, {} )

unless you knew some other specific metaclass were to be used
(but normally classes get the metaclass of their leftmost base
class, unless they define a __metaclass__ attribute in their
body, so this is the "normal" case and also, I think, what you
would get by calling new.classobj).

Personally, I tend to reach for module new out of habit (it's
also slightly more concise and arguably marginaly clearer in
this specific case), but I gather that calling type objects
directly is the coming thing and module new may end up being
deprecated (as uselessly duplicating this functionality) soon.


More information about the Python-list mailing list