How parametrize classes by class data?

Arnaud Delobelle arnodel at gmail.com
Mon Oct 4 19:07:14 CEST 2010


kj <no.email at please.post> writes:

> I want to implement a "class of classes", so that, instead of the
> usual:
>
> spam = MyClass(eggs)
>
> ...I can write
>
> spam = MyClass(ham)(eggs)
>
> ...where ham is a parameter that will end up as the value of a class
> variable of the class returned by MyClass(ham).
>
> In other words, MyClass is a metaclass: a class whose instances
> are themselves classes.
>
> In the immediate use I have for such a metaclass, the parameter is
> going to be a list of lists of headers, which is used by the __init__
> of the generated class to interpret its inputs.


Just use a class factory, i.e. a function that returns a class.

> The standard library's collections.namedtuple needs to do something
> similar to this, so I thought I could learn how to do it in Python
> by studying its source code.  I was surprised to discover that
> collections.namedtuple achieves this class parametrization by
> generating some source code on the fly, from a template, and exec'ing
> it.
>
> This looked to me like a rather un-Pythonic hack, but seeing there
> in the venerable collections module suggested to me that maybe this
> is actually the best way to achieve this effect in Python.  Is this
> so?  If not, please let me know of a better way.

I presume this is done for performance reasons.

-- 
Arnaud



More information about the Python-list mailing list